xref: /titanic_44/usr/src/uts/common/io/scsi/targets/st.c (revision 2a9459bdd821c1cf59590a7a9069ac9c591e8a6b)
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 #include <sys/byteorder.h>
47 
48 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
49 /*
50  * stats maintained only for reads/writes as commands
51  * like rewind etc skew the wait/busy times
52  */
53 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
54 #define	ST_DO_KSTATS(bp, kstat_function) \
55 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
56 		kstat_function(IOSP); \
57 	}
58 
59 #define	ST_DO_ERRSTATS(un, x)  \
60 	if (un->un_errstats) { \
61 		struct st_errstats *stp; \
62 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
63 		stp->x.value.ul++; \
64 	}
65 
66 #define	FILL_SCSI1_LUN(devp, pkt) 					\
67 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
68 		int _lun;						\
69 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
70 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
71 		if (_lun > 0) {						\
72 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
73 			    _lun;					\
74 		}							\
75 	}
76 
77 /*
78  * get an available contig mem header, cp.
79  * when big_enough is true, we will return NULL, if no big enough
80  * contig mem is found.
81  * when big_enough is false, we will try to find cp containing big
82  * enough contig mem. if not found, we will ruturn the last cp available.
83  *
84  * used by st_get_contig_mem()
85  */
86 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
87 	struct contig_mem *tmp_cp = NULL;				\
88 	for ((cp) = (un)->un_contig_mem;				\
89 	    (cp) != NULL;						\
90 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
91 		if (((cp)->cm_len >= (len)) || 				\
92 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
93 			if (tmp_cp == NULL) { 				\
94 				(un)->un_contig_mem = (cp)->cm_next; 	\
95 			} else { 					\
96 				tmp_cp->cm_next = (cp)->cm_next; 	\
97 			} 						\
98 			(cp)->cm_next = NULL; 				\
99 			(un)->un_contig_mem_available_num--; 		\
100 			break; 						\
101 		} 							\
102 	} 								\
103 }
104 
105 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
106 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
107 
108 #define	ONE_K	1024
109 
110 /*
111  * Global External Data Definitions
112  */
113 extern struct scsi_key_strings scsi_cmds[];
114 extern uchar_t	scsi_cdb_size[];
115 
116 /*
117  * Local Static Data
118  */
119 static void *st_state;
120 static char *const st_label = "st";
121 
122 #ifdef	__x86
123 /*
124  * We need to use below DMA attr to alloc physically contiguous
125  * memory to do I/O in big block size
126  */
127 static ddi_dma_attr_t st_contig_mem_dma_attr = {
128 	DMA_ATTR_V0,    /* version number */
129 	0x0,		/* lowest usable address */
130 	0xFFFFFFFFull,  /* high DMA address range */
131 	0xFFFFFFFFull,  /* DMA counter register */
132 	1,		/* DMA address alignment */
133 	1,		/* DMA burstsizes */
134 	1,		/* min effective DMA size */
135 	0xFFFFFFFFull,  /* max DMA xfer size */
136 	0xFFFFFFFFull,  /* segment boundary */
137 	1,		/* s/g list length */
138 	1,		/* granularity of device */
139 	0		/* DMA transfer flags */
140 };
141 
142 static ddi_device_acc_attr_t st_acc_attr = {
143 	DDI_DEVICE_ATTR_V0,
144 	DDI_NEVERSWAP_ACC,
145 	DDI_STRICTORDER_ACC
146 };
147 
148 /* set limitation for the number of contig_mem */
149 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
150 #endif
151 
152 /*
153  * Tunable parameters
154  *
155  * DISCLAIMER
156  * ----------
157  * These parameters are intended for use only in system testing; if you use
158  * them in production systems, you do so at your own risk. Altering any
159  * variable not listed below may cause unpredictable system behavior.
160  *
161  * st_check_media_time
162  *
163  *   Three second state check
164  *
165  * st_allow_large_xfer
166  *
167  *   Gated with ST_NO_RECSIZE_LIMIT
168  *
169  *   0 - Transfers larger than 64KB will not be allowed
170  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
171  *   1 - Transfers larger than 64KB will be allowed
172  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
173  *
174  * st_report_soft_errors_on_close
175  *
176  *  Gated with ST_SOFT_ERROR_REPORTING
177  *
178  *  0 - Errors will not be reported on close regardless
179  *      of the setting of ST_SOFT_ERROR_REPORTING
180  *
181  *  1 - Errors will be reported on close if
182  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
183  */
184 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
185 static int st_retry_count	= ST_RETRY_COUNT;
186 
187 static int st_io_time		= ST_IO_TIME;
188 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
189 
190 static int st_space_time	= ST_SPACE_TIME;
191 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
192 
193 static int st_error_level	= SCSI_ERR_RETRYABLE;
194 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
195 
196 static int st_max_throttle	= ST_MAX_THROTTLE;
197 
198 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
199 
200 static int st_allow_large_xfer = 1;
201 static int st_report_soft_errors_on_close = 1;
202 
203 /*
204  * End of tunable parameters list
205  */
206 
207 
208 
209 /*
210  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
211  *
212  * Asynchronous I/O's main offering is that it is a non-blocking way to do
213  * reads and writes.  The driver will queue up all the requests it gets and
214  * have them ready to transport to the HBA.  Unfortunately, we cannot always
215  * just ship the I/O requests to the HBA, as there errors and exceptions
216  * that may happen when we don't want the HBA to continue.  Therein comes
217  * the flush-on-errors capability.  If the HBA supports it, then st will
218  * send in st_max_throttle I/O requests at the same time.
219  *
220  * Persistent errors : This was also reasonably simple.  In the interrupt
221  * routines, if there was an error or exception (FM, LEOT, media error,
222  * transport error), the persistent error bits are set and shuts everything
223  * down, but setting the throttle to zero.  If we hit and exception in the
224  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
225  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
226  * the appropriate error, and this will preserve order. Of course, depending
227  * on the exception we have to show a zero read or write before we show
228  * errors back to the application.
229  */
230 
231 extern const int st_ndrivetypes;	/* defined in st_conf.c */
232 extern const struct st_drivetype st_drivetypes[];
233 extern const char st_conf_version[];
234 
235 #ifdef STDEBUG
236 static int st_soft_error_report_debug = 0;
237 volatile int st_debug = 0;
238 #endif
239 
240 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
241 
242 static const struct vid_drivetype {
243 	char	*vid;
244 	char	type;
245 } st_vid_dt[] = {
246 	{"LTO-CVE ",	MT_LTO},
247 	{"QUANTUM ",    MT_ISDLT},
248 	{"SONY    ",    MT_ISAIT},
249 	{"STK     ",	MT_ISSTK9840}
250 };
251 
252 static const struct driver_minor_data {
253 	char	*name;
254 	int	minor;
255 } st_minor_data[] = {
256 	/*
257 	 * The top 4 entries are for the default densities,
258 	 * don't alter their position.
259 	 */
260 	{"",	0},
261 	{"n",	MT_NOREWIND},
262 	{"b",	MT_BSD},
263 	{"bn",	MT_NOREWIND | MT_BSD},
264 	{"l",	MT_DENSITY1},
265 	{"m",	MT_DENSITY2},
266 	{"h",	MT_DENSITY3},
267 	{"c",	MT_DENSITY4},
268 	{"u",	MT_DENSITY4},
269 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
270 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
271 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
272 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
273 	{"un",	MT_DENSITY4 | MT_NOREWIND},
274 	{"lb",	MT_DENSITY1 | MT_BSD},
275 	{"mb",	MT_DENSITY2 | MT_BSD},
276 	{"hb",	MT_DENSITY3 | MT_BSD},
277 	{"cb",	MT_DENSITY4 | MT_BSD},
278 	{"ub",	MT_DENSITY4 | MT_BSD},
279 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
280 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
281 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
282 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
283 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
284 };
285 
286 /* strings used in many debug and warning messages */
287 static const char wr_str[]  = "write";
288 static const char rd_str[]  = "read";
289 static const char wrg_str[] = "writing";
290 static const char rdg_str[] = "reading";
291 static const char *space_strs[] = {
292 	"records",
293 	"filemarks",
294 	"sequential filemarks",
295 	"eod",
296 	"setmarks",
297 	"sequential setmarks",
298 	"Reserved",
299 	"Reserved"
300 };
301 
302 /* default density offsets in the table above */
303 #define	DEF_BLANK	0
304 #define	DEF_NOREWIND	1
305 #define	DEF_BSD		2
306 #define	DEF_BSD_NR	3
307 
308 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
309 
310 static struct tape_failure_code {
311 	uchar_t key;
312 	uchar_t add_code;
313 	uchar_t qual_code;
314 } st_tape_failure_code[] = {
315 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
316 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
317 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
318 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
319 	{ KEY_NOT_READY, 0x53, 0x00},
320 	{ 0xff}
321 };
322 
323 /*  clean bit position and mask */
324 
325 static struct cln_bit_position {
326 	ushort_t cln_bit_byte;
327 	uchar_t cln_bit_mask;
328 } st_cln_bit_position[] = {
329 	{ 21, 0x08},
330 	{ 70, 0xc0},
331 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
332 };
333 
334 /*
335  * architecture dependent allocation restrictions. For x86, we'll set
336  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
337  * st_sgl_size during _init().
338  */
339 #if defined(__sparc)
340 static ddi_dma_attr_t st_alloc_attr = {
341 	DMA_ATTR_V0,	/* version number */
342 	0x0,		/* lowest usable address */
343 	0xFFFFFFFFull,	/* high DMA address range */
344 	0xFFFFFFFFull,	/* DMA counter register */
345 	1,		/* DMA address alignment */
346 	1,		/* DMA burstsizes */
347 	1,		/* min effective DMA size */
348 	0xFFFFFFFFull,	/* max DMA xfer size */
349 	0xFFFFFFFFull,	/* segment boundary */
350 	1,		/* s/g list length */
351 	512,		/* granularity of device */
352 	0		/* DMA transfer flags */
353 };
354 #elif defined(__x86)
355 static ddi_dma_attr_t st_alloc_attr = {
356 	DMA_ATTR_V0,	/* version number */
357 	0x0,		/* lowest usable address */
358 	0x0,		/* high DMA address range [set in _init()] */
359 	0xFFFFull,	/* DMA counter register */
360 	512,		/* DMA address alignment */
361 	1,		/* DMA burstsizes */
362 	1,		/* min effective DMA size */
363 	0xFFFFFFFFull,	/* max DMA xfer size */
364 	0xFFFFFFFFull,  /* segment boundary */
365 	0,		/* s/g list length */
366 	512,		/* granularity of device [set in _init()] */
367 	0		/* DMA transfer flags */
368 };
369 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
370 int st_sgl_size = 0xF;
371 
372 #endif
373 
374 /*
375  * Configuration Data:
376  *
377  * Device driver ops vector
378  */
379 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
380 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
381 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
382 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
383 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
384 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
385 static int st_strategy(struct buf *bp);
386 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
387 	cred_t *cred_p, int *rval_p);
388 extern int nulldev(), nodev();
389 
390 static struct cb_ops st_cb_ops = {
391 	st_open,		/* open */
392 	st_close,		/* close */
393 	st_strategy,		/* strategy */
394 	nodev,			/* print */
395 	nodev,			/* dump */
396 	st_read,		/* read */
397 	st_write,		/* write */
398 	st_ioctl,		/* ioctl */
399 	nodev,			/* devmap */
400 	nodev,			/* mmap */
401 	nodev,			/* segmap */
402 	nochpoll,		/* poll */
403 	ddi_prop_op,		/* cb_prop_op */
404 	0,			/* streamtab  */
405 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
406 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
407 	CB_REV,			/* cb_rev */
408 	st_aread, 		/* async I/O read entry point */
409 	st_awrite		/* async I/O write entry point */
410 
411 };
412 
413 static int stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
414 		void **result);
415 static int st_probe(dev_info_t *dev);
416 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
417 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
418 
419 static struct dev_ops st_ops = {
420 	DEVO_REV,		/* devo_rev, */
421 	0,			/* refcnt  */
422 	stinfo,			/* info */
423 	nulldev,		/* identify */
424 	st_probe,		/* probe */
425 	st_attach,		/* attach */
426 	st_detach,		/* detach */
427 	nodev,			/* reset */
428 	&st_cb_ops,		/* driver operations */
429 	(struct bus_ops *)0,	/* bus operations */
430 	nulldev			/* power */
431 };
432 
433 /*
434  * Local Function Declarations
435  */
436 static char *st_print_scsi_cmd(char cmd);
437 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
438     char *title, char *cdb);
439 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
440 	char *title, char *data, int len);
441 static int st_doattach(struct scsi_device *devp, int (*canwait)());
442 static void st_known_tape_type(struct scsi_tape *un);
443 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
444     struct st_drivetype *);
445 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
446     struct st_drivetype *);
447 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
448     struct st_drivetype *);
449 static int st_get_densities_from_tape_drive(struct scsi_tape *,
450     struct st_drivetype *);
451 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
452     struct st_drivetype *);
453 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
454     ushort_t);
455 static int st_get_default_conf(struct scsi_tape *, char *,
456     struct st_drivetype *);
457 static int st_rw(dev_t dev, struct uio *uio, int flag);
458 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
459 static int st_find_eod(dev_t dev);
460 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
461 static int st_ioctl_cmd(dev_t dev, struct uscsi_cmd *, int flag);
462 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
463 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
464 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
465 static void st_start(struct scsi_tape *un);
466 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
467     clock_t timeout_interval);
468 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
469     clock_t timeout_interval);
470 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
471 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
472 static void st_init(struct scsi_tape *un);
473 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
474     int (*func)(caddr_t));
475 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
476     struct buf *bp, int (*func)(caddr_t));
477 static void st_intr(struct scsi_pkt *pkt);
478 static void st_set_state(struct scsi_tape *un);
479 static void st_test_append(struct buf *bp);
480 static int st_runout(caddr_t);
481 static int st_cmd(dev_t dev, int com, int count, int wait);
482 static int st_set_compression(struct scsi_tape *un);
483 static int st_write_fm(dev_t dev, int wfm);
484 static int st_determine_generic(dev_t dev);
485 static int st_determine_density(dev_t dev, int rw);
486 static int st_get_density(dev_t dev);
487 static int st_set_density(dev_t dev);
488 static int st_loadtape(dev_t dev);
489 static int st_modesense(struct scsi_tape *un);
490 static int st_modeselect(struct scsi_tape *un);
491 static int st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
492 static int st_wrongtapetype(struct scsi_tape *un);
493 static int st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
494 static int st_handle_sense(struct scsi_tape *un, struct buf *bp);
495 static int st_handle_autosense(struct scsi_tape *un, struct buf *bp);
496 static int st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
497     struct scsi_status *);
498 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
499 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
500     struct scsi_arq_status *cmd);
501 static void st_empty_error_stack(struct scsi_tape *un);
502 static int st_report_soft_errors(dev_t dev, int flag);
503 static void st_delayed_cv_broadcast(void *arg);
504 static int st_check_media(dev_t dev, enum mtio_state state);
505 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
506 static void st_intr_restart(void *arg);
507 static void st_start_restart(void *arg);
508 static int st_gen_mode_sense(struct scsi_tape *un, int page,
509     struct seq_mode *page_data, int page_size);
510 static int st_change_block_size(dev_t dev, uint32_t nblksz);
511 static int st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
512     int page_size);
513 static int st_read_block_limits(struct scsi_tape *un,
514     struct read_blklim *read_blk);
515 static int st_report_density_support(struct scsi_tape *un,
516     uchar_t *density_data, size_t buflen);
517 static int st_report_supported_operation(struct scsi_tape *un,
518     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
519 static int st_tape_init(dev_t dev);
520 static void st_flush(struct scsi_tape *un);
521 static void st_set_pe_errno(struct scsi_tape *un);
522 static void st_hba_unflush(struct scsi_tape *un);
523 static void st_turn_pe_on(struct scsi_tape *un);
524 static void st_turn_pe_off(struct scsi_tape *un);
525 static void st_set_pe_flag(struct scsi_tape *un);
526 static void st_clear_pe(struct scsi_tape *un);
527 static void st_wait_for_io(struct scsi_tape *un);
528 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
529 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
530 static int st_reserve_release(struct scsi_tape *un, int command);
531 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb);
532 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
533     int count);
534 static int st_take_ownership(dev_t dev);
535 static int st_check_asc_ascq(struct scsi_tape *un);
536 static int st_check_clean_bit(dev_t dev);
537 static int st_check_alert_flags(dev_t dev);
538 static int st_check_sequential_clean_bit(dev_t dev);
539 static int st_check_sense_clean_bit(dev_t dev);
540 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
541 static void st_calculate_timeouts(struct scsi_tape *un);
542 static writablity st_is_drive_worm(struct scsi_tape *un);
543 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
544     caddr_t buf, size_t size);
545 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
546     caddr_t dest, uchar_t page);
547 static int st_update_block_pos(struct scsi_tape *un);
548 static int st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
549     size_t data_sz, caddr_t responce);
550 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
551 static int st_logical_block_locate(struct scsi_tape *un, uint64_t lblk,
552     uchar_t partition);
553 static int st_mtfsf_ioctl(struct scsi_tape *un, int files);
554 static int st_mtfsr_ioctl(struct scsi_tape *un, int count);
555 static int st_mtbsf_ioctl(struct scsi_tape *un, int files);
556 static int st_mtnbsf_ioctl(struct scsi_tape *un, int count);
557 static int st_mtbsr_ioctl(struct scsi_tape *un, int num);
558 static int st_mtfsfm_ioctl(struct scsi_tape *un, int cnt);
559 static int st_mtbsfm_ioctl(struct scsi_tape *un, int cnt);
560 static int st_backward_space_files(struct scsi_tape *un, int count,
561     int infront);
562 static int st_forward_space_files(struct scsi_tape *un, int files);
563 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
564     int32_t fileno);
565 static int st_space_to_begining_of_file(struct scsi_tape *un);
566 static int st_space_records(struct scsi_tape *un, int records);
567 
568 #ifdef	__x86
569 /*
570  * routines for I/O in big block size
571  */
572 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
573 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
574     int alloc_flags);
575 static int st_bigblk_xfer_done(struct buf *bp);
576 static struct buf *st_get_bigblk_bp(struct buf *bp);
577 #endif
578 static void st_print_position(struct scsi_tape *un, const char *comment,
579     tapepos_t *pos);
580 
581 /*
582  * error statistics create/update functions
583  */
584 static int st_create_errstats(struct scsi_tape *, int);
585 static int st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos);
586 
587 #ifdef STDEBUG
588 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
589 static char *st_dev_name(dev_t dev);
590 #endif /* STDEBUG */
591 
592 #if !defined(lint)
593 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
594     scsi_pkt buf uio scsi_cdb uscsi_cmd))
595 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
596 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
597 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
598 #endif
599 
600 /*
601  * autoconfiguration routines.
602  */
603 char _depends_on[] = "misc/scsi";
604 
605 static struct modldrv modldrv = {
606 	&mod_driverops,		/* Type of module. This one is a driver */
607 	"SCSI tape Driver %I%", /* Name of the module. */
608 	&st_ops			/* driver ops */
609 };
610 
611 static struct modlinkage modlinkage = {
612 	MODREV_1, &modldrv, NULL
613 };
614 
615 /*
616  * Notes on Post Reset Behavior in the tape driver:
617  *
618  * When the tape drive is opened, the driver  attempts  to make sure that
619  * the tape head is positioned exactly where it was left when it was last
620  * closed  provided  the  medium  is not  changed.  If the tape  drive is
621  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
622  * of position due to reset) will happen when the first tape operation or
623  * I/O occurs.  The repositioning (if required) may not be possible under
624  * certain situations such as when the device firmware not able to report
625  * the medium  change in the REQUEST  SENSE data  because of a reset or a
626  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
627  * extraordinary  situations, where the driver fails to position the head
628  * at its  original  position,  it will fail the open the first  time, to
629  * save the applications from overwriting the data.  All further attempts
630  * to open the tape device will result in the driver  attempting  to load
631  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
632  * indicate  that further  attempts to open the tape device may result in
633  * the tape being  loaded at BOT will be printed on the  console.  If the
634  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
635  * original tape head  position,  will result in the failure of the first
636  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
637  * internal tape position  which will  necessitate  the  applications  to
638  * validate the position by using either a tape  positioning  ioctl (such
639  * as MTREW) or closing and reopening the tape device.
640  *
641  */
642 
643 int
644 _init(void)
645 {
646 	int	e;
647 
648 	if (((e = ddi_soft_state_init(&st_state,
649 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
650 		return (e);
651 	}
652 
653 	if ((e = mod_install(&modlinkage)) != 0) {
654 		ddi_soft_state_fini(&st_state);
655 	}
656 
657 #if defined(__x86)
658 	/* set the max physical address for iob allocs on x86 */
659 	st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
660 
661 	/*
662 	 * set the sgllen for iob allocs on x86. If this is set less than
663 	 * the number of pages the buffer will take (taking into account
664 	 * alignment), it would force the allocator to try and allocate
665 	 * contiguous pages.
666 	 */
667 	st_alloc_attr.dma_attr_sgllen = st_sgl_size;
668 #endif
669 
670 	return (e);
671 }
672 
673 int
674 _fini(void)
675 {
676 	int e;
677 
678 	if ((e = mod_remove(&modlinkage)) != 0) {
679 		return (e);
680 	}
681 
682 	ddi_soft_state_fini(&st_state);
683 
684 	return (e);
685 }
686 
687 int
688 _info(struct modinfo *modinfop)
689 {
690 	return (mod_info(&modlinkage, modinfop));
691 }
692 
693 
694 static int
695 st_probe(dev_info_t *devi)
696 {
697 	int instance;
698 	struct scsi_device *devp;
699 	int rval;
700 
701 #if !defined(__sparc)
702 	char    *tape_prop;
703 	int	tape_prop_len;
704 #endif
705 
706 	ST_ENTR(devi, st_probe);
707 
708 	/* If self identifying device */
709 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
710 		return (DDI_PROBE_DONTCARE);
711 	}
712 
713 #if !defined(__sparc)
714 	/*
715 	 * Since some x86 HBAs have devnodes that look like SCSI as
716 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
717 	 * we check for the presence of the "tape" property.
718 	 */
719 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
720 	    DDI_PROP_CANSLEEP, "tape",
721 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
722 		return (DDI_PROBE_FAILURE);
723 	}
724 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
725 		kmem_free(tape_prop, tape_prop_len);
726 		return (DDI_PROBE_FAILURE);
727 	}
728 	kmem_free(tape_prop, tape_prop_len);
729 #endif
730 
731 	devp = ddi_get_driver_private(devi);
732 	instance = ddi_get_instance(devi);
733 
734 	if (ddi_get_soft_state(st_state, instance) != NULL) {
735 		return (DDI_PROBE_PARTIAL);
736 	}
737 
738 
739 	/*
740 	 * Turn around and call probe routine to see whether
741 	 * we actually have a tape at this SCSI nexus.
742 	 */
743 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
744 
745 		/*
746 		 * In checking the whole inq_dtype byte we are looking at both
747 		 * the Peripheral Qualifier and the Peripheral Device Type.
748 		 * For this driver we are only interested in sequential devices
749 		 * that are connected or capable if connecting to this logical
750 		 * unit.
751 		 */
752 		if (devp->sd_inq->inq_dtype ==
753 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
754 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
755 			    "probe exists\n");
756 			rval = DDI_PROBE_SUCCESS;
757 		} else {
758 			rval = DDI_PROBE_FAILURE;
759 		}
760 	} else {
761 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
762 		    "probe failure: nothing there\n");
763 		rval = DDI_PROBE_FAILURE;
764 	}
765 	scsi_unprobe(devp);
766 	return (rval);
767 }
768 
769 static int
770 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
771 {
772 	int 	instance;
773 	int	wide;
774 	int 	dev_instance;
775 	int	ret_status;
776 	struct	scsi_device *devp;
777 	int	node_ix;
778 	struct	scsi_tape *un;
779 
780 	ST_ENTR(devi, st_attach);
781 
782 	devp = ddi_get_driver_private(devi);
783 	instance = ddi_get_instance(devi);
784 
785 	switch (cmd) {
786 		case DDI_ATTACH:
787 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
788 				return (DDI_FAILURE);
789 			}
790 			break;
791 		case DDI_RESUME:
792 			/*
793 			 * Suspend/Resume
794 			 *
795 			 * When the driver suspended, there might be
796 			 * outstanding cmds and therefore we need to
797 			 * reset the suspended flag and resume the scsi
798 			 * watch thread and restart commands and timeouts
799 			 */
800 
801 			if (!(un = ddi_get_soft_state(st_state, instance))) {
802 				return (DDI_FAILURE);
803 			}
804 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
805 			    un->un_dev);
806 
807 			mutex_enter(ST_MUTEX);
808 
809 			un->un_throttle = un->un_max_throttle;
810 			un->un_tids_at_suspend = 0;
811 			un->un_pwr_mgmt = ST_PWR_NORMAL;
812 
813 			if (un->un_swr_token) {
814 				scsi_watch_resume(un->un_swr_token);
815 			}
816 
817 			/*
818 			 * Restart timeouts
819 			 */
820 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
821 				mutex_exit(ST_MUTEX);
822 				un->un_delay_tid = timeout(
823 				    st_delayed_cv_broadcast, un,
824 				    drv_usectohz((clock_t)
825 				    MEDIA_ACCESS_DELAY));
826 				mutex_enter(ST_MUTEX);
827 			}
828 
829 			if (un->un_tids_at_suspend & ST_HIB_TID) {
830 				mutex_exit(ST_MUTEX);
831 				un->un_hib_tid = timeout(st_intr_restart, un,
832 				    ST_STATUS_BUSY_TIMEOUT);
833 				mutex_enter(ST_MUTEX);
834 			}
835 
836 			ret_status = st_clear_unit_attentions(dev_instance, 5);
837 
838 			/*
839 			 * now check if we need to restore the tape position
840 			 */
841 			if ((un->un_suspend_pos.pmode != invalid) &&
842 			    ((un->un_suspend_pos.fileno > 0) ||
843 			    (un->un_suspend_pos.blkno > 0)) ||
844 			    (un->un_suspend_pos.lgclblkno > 0)) {
845 				if (ret_status != 0) {
846 					/*
847 					 * tape didn't get good TUR
848 					 * just print out error messages
849 					 */
850 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
851 					    "st_attach-RESUME: tape failure "
852 					    " tape position will be lost");
853 				} else {
854 					/* this prints errors */
855 					(void) st_validate_tapemarks(un,
856 					    &un->un_suspend_pos);
857 				}
858 				/*
859 				 * there are no retries, if there is an error
860 				 * we don't know if the tape has changed
861 				 */
862 				un->un_suspend_pos.pmode = invalid;
863 			}
864 
865 			/* now we are ready to start up any queued I/Os */
866 			if (un->un_ncmds || un->un_quef) {
867 				st_start(un);
868 			}
869 
870 			cv_broadcast(&un->un_suspend_cv);
871 			mutex_exit(ST_MUTEX);
872 			return (DDI_SUCCESS);
873 
874 		default:
875 			return (DDI_FAILURE);
876 	}
877 
878 	un = ddi_get_soft_state(st_state, instance);
879 
880 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
881 	    "st_attach: instance=%x\n", instance);
882 
883 	/*
884 	 * Add a zero-length attribute to tell the world we support
885 	 * kernel ioctls (for layered drivers)
886 	 */
887 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
888 	    DDI_KERNEL_IOCTL, NULL, 0);
889 
890 	ddi_report_dev((dev_info_t *)devi);
891 
892 	/*
893 	 * If it's a SCSI-2 tape drive which supports wide,
894 	 * tell the host adapter to use wide.
895 	 */
896 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
897 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
898 
899 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
900 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
901 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
902 	}
903 
904 	/*
905 	 * enable autorequest sense; keep the rq packet around in case
906 	 * the autorequest sense fails because of a busy condition
907 	 * do a getcap first in case the capability is not variable
908 	 */
909 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
910 		un->un_arq_enabled = 1;
911 	} else {
912 		un->un_arq_enabled =
913 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
914 	}
915 
916 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
917 	    (un->un_arq_enabled ? "enabled" : "disabled"));
918 
919 	un->un_untagged_qing =
920 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
921 
922 	/*
923 	 * XXX - This is just for 2.6.  to tell users that write buffering
924 	 *	has gone away.
925 	 */
926 	if (un->un_arq_enabled && un->un_untagged_qing) {
927 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
928 		    "tape-driver-buffering", 0) != 0) {
929 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
930 			    "Write Data Buffering has been depricated. Your "
931 			    "applications should continue to work normally.\n"
932 			    " But, they should  ported to use Asynchronous "
933 			    " I/O\n"
934 			    " For more information, read about "
935 			    " tape-driver-buffering "
936 			    "property in the st(7d) man page\n");
937 		}
938 	}
939 
940 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
941 	un->un_flush_on_errors = 0;
942 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
943 
944 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
945 	    "throttle=%x, max_throttle = %x\n",
946 	    un->un_throttle, un->un_max_throttle);
947 
948 	/* initialize persistent errors to nil */
949 	un->un_persistence = 0;
950 	un->un_persist_errors = 0;
951 
952 	/*
953 	 * Get dma-max from HBA driver. If it is not defined, use 64k
954 	 */
955 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
956 	if (un->un_maxdma == -1) {
957 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
958 		    "Received a value that looked like -1. Using 64k maxdma");
959 		un->un_maxdma = (64 * ONE_K);
960 	}
961 
962 #ifdef	__x86
963 	/*
964 	 * for x86, the device may be able to DMA more than the system will
965 	 * allow under some circumstances. We need account for both the HBA's
966 	 * and system's contraints.
967 	 *
968 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
969 	 * device constraints, the max copy buffer size, and the worse case
970 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
971 	 * doesn't take the worse case framentation into account.
972 	 *
973 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
974 	 * if none of the pages are contiguous. Keeping track of both of these
975 	 * values allows us to support larger tape block sizes on some devices.
976 	 */
977 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
978 	    1);
979 
980 	/*
981 	 * If the dma-max-arch capability is not implemented, or the value
982 	 * comes back higher than what was reported in dma-max, use dma-max.
983 	 */
984 	if ((un->un_maxdma_arch == -1) ||
985 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
986 		un->un_maxdma_arch = un->un_maxdma;
987 	}
988 #endif
989 
990 	/*
991 	 * Get the max allowable cdb size
992 	 */
993 	un->un_max_cdb_sz =
994 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
995 	if (un->un_max_cdb_sz < CDB_GROUP0) {
996 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
997 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
998 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
999 	}
1000 
1001 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1002 
1003 	un->un_mediastate = MTIO_NONE;
1004 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1005 
1006 	/*
1007 	 * initialize kstats
1008 	 */
1009 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1010 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1011 	if (un->un_stats) {
1012 		un->un_stats->ks_lock = ST_MUTEX;
1013 		kstat_install(un->un_stats);
1014 	}
1015 	(void) st_create_errstats(un, instance);
1016 
1017 	/*
1018 	 * find the drive type for this target
1019 	 */
1020 	mutex_enter(ST_MUTEX);
1021 	un->un_dev = MT_TEM_DEV(instance);
1022 	st_known_tape_type(un);
1023 	un->un_dev = 0;
1024 	mutex_exit(ST_MUTEX);
1025 
1026 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1027 		int minor;
1028 		char *name;
1029 
1030 		name  = st_minor_data[node_ix].name;
1031 		minor = st_minor_data[node_ix].minor;
1032 
1033 		/*
1034 		 * For default devices set the density to the
1035 		 * preferred default density for this device.
1036 		 */
1037 		if (node_ix <= DEF_BSD_NR) {
1038 			minor |= un->un_dp->default_density;
1039 		}
1040 		minor |= MTMINOR(instance);
1041 
1042 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1043 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1044 			continue;
1045 		}
1046 
1047 		ddi_remove_minor_node(devi, NULL);
1048 
1049 		cv_destroy(&un->un_clscv);
1050 		cv_destroy(&un->un_sbuf_cv);
1051 		cv_destroy(&un->un_queue_cv);
1052 		cv_destroy(&un->un_state_cv);
1053 		cv_destroy(&un->un_suspend_cv);
1054 		cv_destroy(&un->un_tape_busy_cv);
1055 
1056 		if (un->un_sbufp) {
1057 			freerbuf(un->un_sbufp);
1058 		}
1059 		if (un->un_uscsi_rqs_buf) {
1060 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1061 		}
1062 		if (un->un_mspl) {
1063 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1064 		}
1065 		if (un->un_dp_size) {
1066 			kmem_free(un->un_dp, un->un_dp_size);
1067 		}
1068 		if (un->un_state) {
1069 			kstat_delete(un->un_stats);
1070 		}
1071 		if (un->un_errstats) {
1072 			kstat_delete(un->un_errstats);
1073 		}
1074 
1075 		scsi_destroy_pkt(un->un_rqs);
1076 		scsi_free_consistent_buf(un->un_rqs_bp);
1077 		ddi_soft_state_free(st_state, instance);
1078 		devp->sd_private = NULL;
1079 		devp->sd_sense = NULL;
1080 
1081 		ddi_prop_remove_all(devi);
1082 		return (DDI_FAILURE);
1083 	}
1084 
1085 	return (DDI_SUCCESS);
1086 }
1087 
1088 /*
1089  * st_detach:
1090  *
1091  * we allow a detach if and only if:
1092  *	- no tape is currently inserted
1093  *	- tape position is at BOT or unknown
1094  *		(if it is not at BOT then a no rewind
1095  *		device was opened and we have to preserve state)
1096  *	- it must be in a closed state : no timeouts or scsi_watch requests
1097  *		will exist if it is closed, so we don't need to check for
1098  *		them here.
1099  */
1100 /*ARGSUSED*/
1101 static int
1102 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1103 {
1104 	int 	instance;
1105 	int 	dev_instance;
1106 	struct scsi_device *devp;
1107 	struct scsi_tape *un;
1108 	clock_t wait_cmds_complete;
1109 
1110 	ST_ENTR(devi, st_detach);
1111 
1112 	instance = ddi_get_instance(devi);
1113 
1114 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1115 		return (DDI_FAILURE);
1116 	}
1117 
1118 	mutex_enter(ST_MUTEX);
1119 
1120 	/*
1121 	 * Clear error entry stack
1122 	 */
1123 	st_empty_error_stack(un);
1124 
1125 	mutex_exit(ST_MUTEX);
1126 
1127 	switch (cmd) {
1128 
1129 	case DDI_DETACH:
1130 		/*
1131 		 * Undo what we did in st_attach & st_doattach,
1132 		 * freeing resources and removing things we installed.
1133 		 * The system framework guarantees we are not active
1134 		 * with this devinfo node in any other entry points at
1135 		 * this time.
1136 		 */
1137 
1138 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1139 		    "st_detach: instance=%x, un=%p\n", instance,
1140 		    (void *)un);
1141 
1142 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1143 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1144 		    (un->un_state != ST_STATE_CLOSED)) {
1145 			/*
1146 			 * we cannot unload some targets because the
1147 			 * inquiry returns junk unless immediately
1148 			 * after a reset
1149 			 */
1150 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1151 			    "cannot unload instance %x\n", instance);
1152 			return (DDI_FAILURE);
1153 		}
1154 
1155 		/*
1156 		 * if the tape has been removed then we may unload;
1157 		 * do a test unit ready and if it returns NOT READY
1158 		 * then we assume that it is safe to unload.
1159 		 * as a side effect, pmode may be set to invalid if the
1160 		 * the test unit ready fails;
1161 		 * also un_state may be set to non-closed, so reset it
1162 		 */
1163 		if ((un->un_dev) &&		/* Been opened since attach */
1164 		    ((un->un_pos.pmode == legacy) &&
1165 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1166 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1167 		    ((un->un_pos.pmode == logical) &&
1168 		    (un->un_pos.lgclblkno > 0))) {
1169 			mutex_enter(ST_MUTEX);
1170 			/*
1171 			 * Send Test Unit Ready in the hopes that if
1172 			 * the drive is not in the state we think it is.
1173 			 * And the state will be changed so it can be detached.
1174 			 * If the command fails to reach the device and
1175 			 * the drive was not rewound or unloaded we want
1176 			 * to fail the detach till a user command fails
1177 			 * where after the detach will succead.
1178 			 */
1179 			(void) st_cmd(un->un_dev, SCMD_TEST_UNIT_READY,
1180 			    0, SYNC_CMD);
1181 			/*
1182 			 * After TUR un_state may be set to non-closed,
1183 			 * so reset it back.
1184 			 */
1185 			un->un_state = ST_STATE_CLOSED;
1186 			mutex_exit(ST_MUTEX);
1187 		}
1188 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1189 		    "un_status=%x, fileno=%x, blkno=%x\n",
1190 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1191 
1192 		/*
1193 		 * check again:
1194 		 * if we are not at BOT then it is not safe to unload
1195 		 */
1196 		if ((un->un_dev) &&		/* Been opened since attach */
1197 		    (((un->un_pos.pmode == legacy) &&
1198 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1199 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1200 		    ((un->un_pos.pmode == logical) &&
1201 		    (un->un_pos.lgclblkno > 0)))) {
1202 
1203 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1204 			    "cannot detach: pmode=%d fileno=%x, blkno=%x"
1205 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1206 			    un->un_pos.fileno, un->un_pos.blkno,
1207 			    un->un_pos.lgclblkno);
1208 			return (DDI_FAILURE);
1209 		}
1210 
1211 		/*
1212 		 * Just To make sure that we have released the
1213 		 * tape unit .
1214 		 */
1215 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1216 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1217 			mutex_enter(ST_MUTEX);
1218 			(void) st_reserve_release(un, ST_RELEASE);
1219 			mutex_exit(ST_MUTEX);
1220 		}
1221 
1222 		/*
1223 		 * now remove other data structures allocated in st_doattach()
1224 		 */
1225 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1226 		    "destroying/freeing\n");
1227 		cv_destroy(&un->un_clscv);
1228 		cv_destroy(&un->un_sbuf_cv);
1229 		cv_destroy(&un->un_queue_cv);
1230 		cv_destroy(&un->un_suspend_cv);
1231 		cv_destroy(&un->un_tape_busy_cv);
1232 
1233 		if (un->un_hib_tid) {
1234 			(void) untimeout(un->un_hib_tid);
1235 			un->un_hib_tid = 0;
1236 		}
1237 
1238 		if (un->un_delay_tid) {
1239 			(void) untimeout(un->un_delay_tid);
1240 			un->un_delay_tid = 0;
1241 		}
1242 		cv_destroy(&un->un_state_cv);
1243 
1244 #ifdef	__x86
1245 		if (un->un_contig_mem_hdl != NULL) {
1246 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1247 		}
1248 #endif
1249 		if (un->un_sbufp) {
1250 			freerbuf(un->un_sbufp);
1251 		}
1252 		if (un->un_uscsi_rqs_buf) {
1253 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1254 		}
1255 		if (un->un_mspl) {
1256 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1257 		}
1258 		if (un->un_rqs) {
1259 			scsi_destroy_pkt(un->un_rqs);
1260 			scsi_free_consistent_buf(un->un_rqs_bp);
1261 		}
1262 		if (un->un_mkr_pkt) {
1263 			scsi_destroy_pkt(un->un_mkr_pkt);
1264 		}
1265 		if (un->un_arq_enabled) {
1266 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1267 		}
1268 		if (un->un_dp_size) {
1269 			kmem_free(un->un_dp, un->un_dp_size);
1270 		}
1271 		if (un->un_stats) {
1272 			kstat_delete(un->un_stats);
1273 			un->un_stats = (kstat_t *)0;
1274 		}
1275 		if (un->un_errstats) {
1276 			kstat_delete(un->un_errstats);
1277 			un->un_errstats = (kstat_t *)0;
1278 		}
1279 		devp = ST_SCSI_DEVP;
1280 		ddi_soft_state_free(st_state, instance);
1281 		devp->sd_private = NULL;
1282 		devp->sd_sense = NULL;
1283 		scsi_unprobe(devp);
1284 		ddi_prop_remove_all(devi);
1285 		ddi_remove_minor_node(devi, NULL);
1286 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1287 		return (DDI_SUCCESS);
1288 
1289 	case DDI_SUSPEND:
1290 
1291 		/*
1292 		 * Suspend/Resume
1293 		 *
1294 		 * To process DDI_SUSPEND, we must do the following:
1295 		 *
1296 		 *  - check ddi_removing_power to see if power will be turned
1297 		 *    off. if so, return DDI_FAILURE
1298 		 *  - check if we are already suspended,
1299 		 *    if so, return DDI_FAILURE
1300 		 *  - check if device state is CLOSED,
1301 		 *    if not, return DDI_FAILURE.
1302 		 *  - wait until outstanding operations complete
1303 		 *  - save tape state
1304 		 *  - block new operations
1305 		 *  - cancel pending timeouts
1306 		 *
1307 		 */
1308 
1309 		if (ddi_removing_power(devi)) {
1310 			return (DDI_FAILURE);
1311 		}
1312 		mutex_enter(ST_MUTEX);
1313 
1314 		/*
1315 		 * Shouldn't already be suspended, if so return failure
1316 		 */
1317 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1318 			mutex_exit(ST_MUTEX);
1319 			return (DDI_FAILURE);
1320 		}
1321 		if (un->un_state != ST_STATE_CLOSED) {
1322 			mutex_exit(ST_MUTEX);
1323 			return (DDI_FAILURE);
1324 		}
1325 
1326 		/*
1327 		 * Wait for all outstanding I/O's to complete
1328 		 *
1329 		 * we wait on both ncmds and the wait queue for times
1330 		 * when we are flushing after persistent errors are
1331 		 * flagged, which is when ncmds can be 0, and the
1332 		 * queue can still have I/O's.  This way we preserve
1333 		 * order of biodone's.
1334 		 */
1335 		wait_cmds_complete = ddi_get_lbolt();
1336 		wait_cmds_complete +=
1337 		    st_wait_cmds_complete * drv_usectohz(1000000);
1338 		while (un->un_ncmds || un->un_quef ||
1339 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1340 
1341 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1342 			    wait_cmds_complete) == -1) {
1343 				/*
1344 				 * Time expired then cancel the command
1345 				 */
1346 				mutex_exit(ST_MUTEX);
1347 				if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
1348 					mutex_enter(ST_MUTEX);
1349 					if (un->un_last_throttle) {
1350 						un->un_throttle =
1351 						    un->un_last_throttle;
1352 					}
1353 					mutex_exit(ST_MUTEX);
1354 					return (DDI_FAILURE);
1355 				} else {
1356 					mutex_enter(ST_MUTEX);
1357 					break;
1358 				}
1359 			}
1360 		}
1361 
1362 		/*
1363 		 * DDI_SUSPEND says that the system "may" power down, we
1364 		 * remember the file and block number before rewinding.
1365 		 * we also need to save state before issuing
1366 		 * any WRITE_FILE_MARK command.
1367 		 */
1368 		(void) st_update_block_pos(un);
1369 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1370 
1371 		dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
1372 		    un->un_dev);
1373 
1374 		/*
1375 		 * Issue a zero write file fmk command to tell the drive to
1376 		 * flush any buffered tape marks
1377 		 */
1378 		(void) st_cmd(dev_instance, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1379 
1380 		/*
1381 		 * Because not all tape drives correctly implement buffer
1382 		 * flushing with the zero write file fmk command, issue a
1383 		 * synchronous rewind command to force data flushing.
1384 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1385 		 * anyway.
1386 		 */
1387 		(void) st_cmd(dev_instance, SCMD_REWIND, 0, SYNC_CMD);
1388 
1389 		/* stop any new operations */
1390 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1391 		un->un_throttle = 0;
1392 
1393 		/*
1394 		 * cancel any outstanding timeouts
1395 		 */
1396 		if (un->un_delay_tid) {
1397 			timeout_id_t temp_id = un->un_delay_tid;
1398 			un->un_delay_tid = 0;
1399 			un->un_tids_at_suspend |= ST_DELAY_TID;
1400 			mutex_exit(ST_MUTEX);
1401 			(void) untimeout(temp_id);
1402 			mutex_enter(ST_MUTEX);
1403 		}
1404 
1405 		if (un->un_hib_tid) {
1406 			timeout_id_t temp_id = un->un_hib_tid;
1407 			un->un_hib_tid = 0;
1408 			un->un_tids_at_suspend |= ST_HIB_TID;
1409 			mutex_exit(ST_MUTEX);
1410 			(void) untimeout(temp_id);
1411 			mutex_enter(ST_MUTEX);
1412 		}
1413 
1414 		/*
1415 		 * Suspend the scsi_watch_thread
1416 		 */
1417 		if (un->un_swr_token) {
1418 			opaque_t temp_token = un->un_swr_token;
1419 			mutex_exit(ST_MUTEX);
1420 			scsi_watch_suspend(temp_token);
1421 		} else {
1422 			mutex_exit(ST_MUTEX);
1423 		}
1424 
1425 		return (DDI_SUCCESS);
1426 
1427 	default:
1428 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1429 		return (DDI_FAILURE);
1430 	}
1431 }
1432 
1433 
1434 /* ARGSUSED */
1435 static int
1436 stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1437 {
1438 	dev_t dev;
1439 	struct scsi_tape *un;
1440 	int instance, error;
1441 
1442 	ST_ENTR(dip, stinfo);
1443 
1444 	switch (infocmd) {
1445 	case DDI_INFO_DEVT2DEVINFO:
1446 		dev = (dev_t)arg;
1447 		instance = MTUNIT(dev);
1448 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1449 			return (DDI_FAILURE);
1450 		*result = (void *) ST_DEVINFO;
1451 		error = DDI_SUCCESS;
1452 		break;
1453 	case DDI_INFO_DEVT2INSTANCE:
1454 		dev = (dev_t)arg;
1455 		instance = MTUNIT(dev);
1456 		*result = (void *)(uintptr_t)instance;
1457 		error = DDI_SUCCESS;
1458 		break;
1459 	default:
1460 		error = DDI_FAILURE;
1461 	}
1462 	return (error);
1463 }
1464 
1465 static int
1466 st_doattach(struct scsi_device *devp, int (*canwait)())
1467 {
1468 	struct scsi_pkt *rqpkt = NULL;
1469 	struct scsi_tape *un = NULL;
1470 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1471 	int instance;
1472 	struct buf *bp;
1473 	size_t rlen;
1474 
1475 	ST_FUNC(devp->sd_dev, st_doattach);
1476 	/*
1477 	 * Call the routine scsi_probe to do some of the dirty work.
1478 	 * If the INQUIRY command succeeds, the field sd_inq in the
1479 	 * device structure will be filled in.
1480 	 */
1481 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1482 	    "st_doattach(): probing\n");
1483 
1484 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1485 
1486 		/*
1487 		 * In checking the whole inq_dtype byte we are looking at both
1488 		 * the Peripheral Qualifier and the Peripheral Device Type.
1489 		 * For this driver we are only interested in sequential devices
1490 		 * that are connected or capable if connecting to this logical
1491 		 * unit.
1492 		 */
1493 		if (devp->sd_inq->inq_dtype ==
1494 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1495 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1496 			    "probe exists\n");
1497 		} else {
1498 			/* Something there but not a tape device */
1499 			scsi_unprobe(devp);
1500 			return (DDI_FAILURE);
1501 		}
1502 	} else {
1503 		/* Nothing there */
1504 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1505 		    "probe failure: nothing there\n");
1506 		scsi_unprobe(devp);
1507 		return (DDI_FAILURE);
1508 	}
1509 
1510 	bp = scsi_alloc_consistent_buf(&devp->sd_address, (struct buf *)NULL,
1511 	    SENSE_LENGTH, B_READ, canwait, NULL);
1512 	if (!bp) {
1513 		goto error;
1514 	}
1515 	rqpkt = scsi_init_pkt(&devp->sd_address, NULL, bp, CDB_GROUP0, 1, 0,
1516 	    PKT_CONSISTENT, canwait, NULL);
1517 	if (!rqpkt) {
1518 		goto error;
1519 	}
1520 	devp->sd_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;
1521 	ASSERT(geterror(bp) == NULL);
1522 
1523 	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
1524 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
1525 	FILL_SCSI1_LUN(devp, rqpkt);
1526 
1527 	/*
1528 	 * The actual unit is present.
1529 	 * Now is the time to fill in the rest of our info..
1530 	 */
1531 	instance = ddi_get_instance(devp->sd_dev);
1532 
1533 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1534 		goto error;
1535 	}
1536 	un = ddi_get_soft_state(st_state, instance);
1537 
1538 	ASSERT(un != NULL);
1539 
1540 	un->un_sbufp = getrbuf(km_flags);
1541 
1542 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1543 
1544 	/*
1545 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1546 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1547 	 * is obsolete and we want more flexibility in controlling the DMA
1548 	 * address constraints.
1549 	 */
1550 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1551 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1552 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1553 
1554 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1555 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1556 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1557 
1558 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1559 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1560 		    "probe partial failure: no space\n");
1561 		goto error;
1562 	}
1563 
1564 	bzero(un->un_mspl, sizeof (struct seq_mode));
1565 
1566 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1567 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1568 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1569 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1570 #ifdef	__x86
1571 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1572 #endif
1573 
1574 	/* Initialize power managemnet condition variable */
1575 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1576 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1577 
1578 	rqpkt->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1579 
1580 	un->un_pos.pmode = invalid;
1581 	rqpkt->pkt_time = st_io_time;
1582 	rqpkt->pkt_comp = st_intr;
1583 	un->un_rqs	= rqpkt;
1584 	un->un_sd	= devp;
1585 	un->un_rqs_bp	= bp;
1586 	un->un_swr_token = (opaque_t)NULL;
1587 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1588 	un->un_wormable = st_is_drive_worm;
1589 	un->un_read_pos_type = LONG_POS;
1590 
1591 	un->un_suspend_pos.pmode = invalid;
1592 
1593 #ifdef	__x86
1594 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1595 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1596 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1597 		    "allocation of contiguous memory dma handle failed!");
1598 		un->un_contig_mem_hdl = NULL;
1599 		goto error;
1600 	}
1601 #endif
1602 
1603 	/*
1604 	 * Since this driver manages devices with "remote" hardware,
1605 	 * i.e. the devices themselves have no "reg" properties,
1606 	 * the SUSPEND/RESUME commands in detach/attach will not be
1607 	 * called by the power management framework unless we request
1608 	 * it by creating a "pm-hardware-state" property and setting it
1609 	 * to value "needs-suspend-resume".
1610 	 */
1611 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1612 	    "pm-hardware-state", "needs-suspend-resume") !=
1613 	    DDI_PROP_SUCCESS) {
1614 
1615 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1616 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1617 		goto error;
1618 	}
1619 
1620 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1621 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1622 
1623 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1624 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1625 		    "failed\n");
1626 		goto error;
1627 	}
1628 
1629 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "probe success\n");
1630 	return (DDI_SUCCESS);
1631 
1632 error:
1633 	devp->sd_sense = NULL;
1634 
1635 	ddi_remove_minor_node(devp->sd_dev, NULL);
1636 	if (un) {
1637 		if (un->un_mspl) {
1638 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1639 		}
1640 		if (un->un_read_pos_data) {
1641 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1642 		}
1643 		if (un->un_sbufp) {
1644 			freerbuf(un->un_sbufp);
1645 		}
1646 		if (un->un_uscsi_rqs_buf) {
1647 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1648 		}
1649 #ifdef	__x86
1650 		if (un->un_contig_mem_hdl != NULL) {
1651 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1652 		}
1653 #endif
1654 		ddi_soft_state_free(st_state, instance);
1655 		devp->sd_private = NULL;
1656 	}
1657 
1658 	if (rqpkt) {
1659 		scsi_destroy_pkt(rqpkt);
1660 	}
1661 
1662 	if (bp) {
1663 		scsi_free_consistent_buf(bp);
1664 	}
1665 
1666 	if (devp->sd_inq) {
1667 		scsi_unprobe(devp);
1668 	}
1669 	return (DDI_FAILURE);
1670 }
1671 
1672 typedef int
1673 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1674 
1675 static cfg_functp config_functs[] = {
1676 	st_get_conf_from_st_dot_conf,
1677 	st_get_conf_from_st_conf_dot_c,
1678 	st_get_conf_from_tape_drive,
1679 	st_get_default_conf
1680 };
1681 
1682 
1683 /*
1684  * determine tape type, using tape-config-list or built-in table or
1685  * use a generic tape config entry
1686  */
1687 static void
1688 st_known_tape_type(struct scsi_tape *un)
1689 {
1690 	struct st_drivetype *dp;
1691 	cfg_functp *config_funct;
1692 	uchar_t reserved;
1693 
1694 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1695 
1696 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1697 	    : ST_RELEASE;
1698 
1699 	/*
1700 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1701 	 *	 no vid & pid inquiry data.  So, we provide one.
1702 	 */
1703 	if (ST_INQUIRY->inq_len == 0 ||
1704 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1705 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1706 	}
1707 
1708 	if (un->un_dp_size == 0) {
1709 		un->un_dp_size = sizeof (struct st_drivetype);
1710 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1711 		un->un_dp = dp;
1712 	} else {
1713 		dp = un->un_dp;
1714 	}
1715 
1716 	un->un_dp->non_motion_timeout = st_io_time;
1717 	/*
1718 	 * Loop through the configuration methods till one works.
1719 	 */
1720 	for (config_funct = &config_functs[0]; ; config_funct++) {
1721 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1722 			break;
1723 		}
1724 	}
1725 
1726 	/*
1727 	 * If we didn't just make up this configuration and
1728 	 * all the density codes are the same..
1729 	 * Set Auto Density over ride.
1730 	 */
1731 	if (*config_funct != st_get_default_conf) {
1732 		/*
1733 		 * If this device is one that is configured and all
1734 		 * densities are the same, This saves doing gets and set
1735 		 * that yield nothing.
1736 		 */
1737 		if ((dp->densities[0]) == (dp->densities[1]) &&
1738 		    (dp->densities[0]) == (dp->densities[2]) &&
1739 		    (dp->densities[0]) == (dp->densities[3])) {
1740 
1741 			dp->options |= ST_AUTODEN_OVERRIDE;
1742 		}
1743 	}
1744 
1745 
1746 	/*
1747 	 * Store tape drive characteristics.
1748 	 */
1749 	un->un_status = 0;
1750 	un->un_attached = 1;
1751 	un->un_init_options = dp->options;
1752 
1753 	/* setup operation time-outs based on options */
1754 	st_calculate_timeouts(un);
1755 
1756 	/* make sure if we are supposed to be variable, make it variable */
1757 	if (dp->options & ST_VARIABLE) {
1758 		dp->bsize = 0;
1759 	}
1760 
1761 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1762 	    : ST_RELEASE)) {
1763 		(void) st_reserve_release(un, reserved);
1764 	}
1765 
1766 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1767 }
1768 
1769 
1770 typedef struct {
1771 	int mask;
1772 	int bottom;
1773 	int top;
1774 	char *name;
1775 } conf_limit;
1776 
1777 static const conf_limit conf_limits[] = {
1778 
1779 	-1,		1,		2,		"conf version",
1780 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1781 	-1,		0,		0xffffff,	"block size",
1782 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1783 	-1,		0,		4,		"number of densities",
1784 	-1,		0,		UINT8_MAX,	"density code",
1785 	-1,		0,		3,		"default density",
1786 	-1,		0,		UINT16_MAX,	"non motion timeout",
1787 	-1,		0,		UINT16_MAX,	"I/O timeout",
1788 	-1,		0,		UINT16_MAX,	"space timeout",
1789 	-1,		0,		UINT16_MAX,	"load timeout",
1790 	-1,		0,		UINT16_MAX,	"unload timeout",
1791 	-1,		0,		UINT16_MAX,	"erase timeout",
1792 	0,		0,		0,		NULL
1793 };
1794 
1795 static int
1796 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1797     const char *conf_name)
1798 {
1799 	int dens;
1800 	int ndens;
1801 	int value;
1802 	int type;
1803 	int count;
1804 	const conf_limit *limit = &conf_limits[0];
1805 
1806 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1807 
1808 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1809 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1810 
1811 	count = list_len;
1812 	type = *list;
1813 	for (;  count && limit->name; count--, list++, limit++) {
1814 
1815 		value = *list;
1816 		if (value & ~limit->mask) {
1817 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1818 			    "%s %s value invalid bits set: 0x%X\n",
1819 			    conf_name, limit->name, value & ~limit->mask);
1820 			*list &= limit->mask;
1821 		} else if (value < limit->bottom) {
1822 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1823 			    "%s %s value too low: value = %d limit %d\n",
1824 			    conf_name, limit->name, value, limit->bottom);
1825 		} else if (value > limit->top) {
1826 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1827 			    "%s %s value too high: value = %d limit %d\n",
1828 			    conf_name, limit->name, value, limit->top);
1829 		} else {
1830 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1831 			    "%s %s value = 0x%X\n",
1832 			    conf_name, limit->name, value);
1833 		}
1834 
1835 		/* If not the number of densities continue */
1836 		if (limit != &conf_limits[4]) {
1837 			continue;
1838 		}
1839 
1840 		/* If number of densities is not in range can't use config */
1841 		if (value < limit->bottom || value > limit->top) {
1842 			return (-1);
1843 		}
1844 
1845 		ndens = min(value, NDENSITIES);
1846 		if ((type == 1) && (list_len - ndens) != 6) {
1847 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1848 			    "%s conf version 1 with %d densities has %d items"
1849 			    " should have %d",
1850 			    conf_name, ndens, list_len, 6 + ndens);
1851 		} else if ((type == 2) && (list_len - ndens) != 13) {
1852 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1853 			    "%s conf version 2 with %d densities has %d items"
1854 			    " should have %d",
1855 			    conf_name, ndens, list_len, 13 + ndens);
1856 		}
1857 
1858 		limit++;
1859 		for (dens = 0; dens < ndens && count; dens++) {
1860 			count--;
1861 			list++;
1862 			value = *list;
1863 			if (value < limit->bottom) {
1864 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1865 				    "%s density[%d] value too low: value ="
1866 				    " 0x%X limit 0x%X\n",
1867 				    conf_name, dens, value, limit->bottom);
1868 			} else if (value > limit->top) {
1869 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1870 				    "%s density[%d] value too high: value ="
1871 				    " 0x%X limit 0x%X\n",
1872 				    conf_name, dens, value, limit->top);
1873 			} else {
1874 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1875 				    "%s density[%d] value = 0x%X\n",
1876 				    conf_name, dens, value);
1877 			}
1878 		}
1879 	}
1880 
1881 	return (0);
1882 }
1883 
1884 static int
1885 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1886     struct st_drivetype *dp)
1887 {
1888 	caddr_t config_list = NULL;
1889 	caddr_t data_list = NULL;
1890 	int	*data_ptr;
1891 	caddr_t vidptr, prettyptr, datanameptr;
1892 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1893 	int config_list_len, data_list_len, len, i;
1894 	int version;
1895 	int found = 0;
1896 
1897 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
1898 
1899 	/*
1900 	 * Determine type of tape controller. Type is determined by
1901 	 * checking the vendor ids of the earlier inquiry command and
1902 	 * comparing those with vids in tape-config-list defined in st.conf
1903 	 */
1904 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1905 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1906 	    != DDI_PROP_SUCCESS) {
1907 		return (found);
1908 	}
1909 
1910 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1911 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1912 
1913 	/*
1914 	 * Compare vids in each triplet - if it matches, get value for
1915 	 * data_name and contruct a st_drivetype struct
1916 	 * tripletlen is not set yet!
1917 	 */
1918 	for (len = config_list_len, vidptr = config_list;
1919 	    len > 0;
1920 	    vidptr += tripletlen, len -= tripletlen) {
1921 
1922 		vidlen = strlen(vidptr);
1923 		prettyptr = vidptr + vidlen + 1;
1924 		prettylen = strlen(prettyptr);
1925 		datanameptr = prettyptr + prettylen + 1;
1926 		datanamelen = strlen(datanameptr);
1927 		tripletlen = vidlen + prettylen + datanamelen + 3;
1928 
1929 		if (vidlen == 0) {
1930 			continue;
1931 		}
1932 
1933 		/*
1934 		 * If inquiry vid dosen't match this triplets vid,
1935 		 * try the next.
1936 		 */
1937 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1938 			continue;
1939 		}
1940 
1941 		/*
1942 		 * if prettylen is zero then use the vid string
1943 		 */
1944 		if (prettylen == 0) {
1945 			prettyptr = vidptr;
1946 			prettylen = vidlen;
1947 		}
1948 
1949 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1950 		    "vid = %s, pretty=%s, dataname = %s\n",
1951 		    vidptr, prettyptr, datanameptr);
1952 
1953 		/*
1954 		 * get the data list
1955 		 */
1956 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1957 		    datanameptr, (caddr_t)&data_list,
1958 		    &data_list_len) != DDI_PROP_SUCCESS) {
1959 			/*
1960 			 * Error in getting property value
1961 			 * print warning!
1962 			 */
1963 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1964 			    "data property (%s) has no value\n",
1965 			    datanameptr);
1966 			continue;
1967 		}
1968 
1969 		/*
1970 		 * now initialize the st_drivetype struct
1971 		 */
1972 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1973 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1974 		(void) strncpy(dp->vid, vidptr, dp->length);
1975 		data_ptr = (int *)data_list;
1976 		/*
1977 		 * check if data is enough for version, type,
1978 		 * bsize, options, # of densities, density1,
1979 		 * density2, ..., default_density
1980 		 */
1981 		if ((data_list_len < 5 * sizeof (int)) ||
1982 		    (data_list_len < 6 * sizeof (int) +
1983 		    *(data_ptr + 4) * sizeof (int))) {
1984 			/*
1985 			 * print warning and skip to next triplet.
1986 			 */
1987 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1988 			    "data property (%s) incomplete\n",
1989 			    datanameptr);
1990 			kmem_free(data_list, data_list_len);
1991 			continue;
1992 		}
1993 
1994 		if (st_validate_conf_data(un, data_ptr,
1995 		    data_list_len / sizeof (int), datanameptr)) {
1996 			kmem_free(data_list, data_list_len);
1997 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1998 			    "data property (%s) rejected\n",
1999 			    datanameptr);
2000 			continue;
2001 		}
2002 
2003 		/*
2004 		 * check version
2005 		 */
2006 		version = *data_ptr++;
2007 		if (version != 1 && version != 2) {
2008 			/* print warning but accept it */
2009 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2010 			    "Version # for data property (%s) "
2011 			    "not set to 1 or 2\n", datanameptr);
2012 		}
2013 
2014 		dp->type    = *data_ptr++;
2015 		dp->bsize   = *data_ptr++;
2016 		dp->options = *data_ptr++;
2017 		dp->options |= ST_DYNAMIC;
2018 		len = *data_ptr++;
2019 		for (i = 0; i < NDENSITIES; i++) {
2020 			if (i < len) {
2021 				dp->densities[i] = *data_ptr++;
2022 			}
2023 		}
2024 		dp->default_density = *data_ptr << 3;
2025 		if (version == 2 &&
2026 		    data_list_len >= (13 + len) * sizeof (int)) {
2027 			data_ptr++;
2028 			dp->non_motion_timeout	= *data_ptr++;
2029 			dp->io_timeout		= *data_ptr++;
2030 			dp->rewind_timeout	= *data_ptr++;
2031 			dp->space_timeout	= *data_ptr++;
2032 			dp->load_timeout	= *data_ptr++;
2033 			dp->unload_timeout	= *data_ptr++;
2034 			dp->erase_timeout	= *data_ptr++;
2035 		}
2036 		kmem_free(data_list, data_list_len);
2037 		found = 1;
2038 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2039 		    "found in st.conf: vid = %s, pretty=%s\n",
2040 		    dp->vid, dp->name);
2041 		break;
2042 	}
2043 
2044 	/*
2045 	 * free up the memory allocated by ddi_getlongprop
2046 	 */
2047 	if (config_list) {
2048 		kmem_free(config_list, config_list_len);
2049 	}
2050 	return (found);
2051 }
2052 
2053 static int
2054 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2055     struct st_drivetype *dp)
2056 {
2057 	int i;
2058 
2059 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2060 	/*
2061 	 * Determine type of tape controller.  Type is determined by
2062 	 * checking the result of the earlier inquiry command and
2063 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2064 	 */
2065 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2066 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2067 
2068 	for (i = 0; i < st_ndrivetypes; i++) {
2069 		if (st_drivetypes[i].length == 0) {
2070 			continue;
2071 		}
2072 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2073 		    st_drivetypes[i].length)) {
2074 			continue;
2075 		}
2076 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2077 		return (1);
2078 	}
2079 	return (0);
2080 }
2081 
2082 static int
2083 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2084     struct st_drivetype *dp)
2085 {
2086 	int bsize;
2087 	ulong_t maxbsize;
2088 	caddr_t buf;
2089 	struct st_drivetype *tem_dp;
2090 	struct read_blklim *blklim;
2091 	int rval;
2092 	int i;
2093 
2094 	ST_FUNC(ST_DEVINFO, st_get_conf_from_type_drive);
2095 
2096 	/*
2097 	 * Determine the type of tape controller. Type is determined by
2098 	 * sending SCSI commands to tape drive and deriving the type from
2099 	 * the returned data.
2100 	 */
2101 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2102 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2103 
2104 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2105 
2106 	/*
2107 	 * Make up a name
2108 	 */
2109 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2110 	tem_dp->name[VIDPIDLEN] = '\0';
2111 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2112 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2113 	/*
2114 	 * 'clean' vendor and product strings of non-printing chars
2115 	 */
2116 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2117 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2118 			tem_dp->name[i] = '.';
2119 		}
2120 	}
2121 
2122 	/*
2123 	 * MODE SENSE to determine block size.
2124 	 */
2125 	un->un_dp->options |= ST_MODE_SEL_COMP;
2126 	rval = st_modesense(un);
2127 	if (rval) {
2128 		if (rval == EACCES) {
2129 			un->un_dp->type = ST_TYPE_INVALID;
2130 			rval = 1;
2131 		} else {
2132 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2133 			rval = 0;
2134 		}
2135 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2136 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2137 		goto exit;
2138 	}
2139 
2140 	/* Can mode sense page 0x10 or 0xf */
2141 	tem_dp->options |= ST_MODE_SEL_COMP;
2142 	bsize = (un->un_mspl->high_bl << 16)	|
2143 	    (un->un_mspl->mid_bl << 8)		|
2144 	    (un->un_mspl->low_bl);
2145 
2146 	if (bsize == 0) {
2147 		tem_dp->options |= ST_VARIABLE;
2148 		tem_dp->bsize = 0;
2149 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2150 		rval = st_change_block_size(un->un_dev, 0);
2151 		if (rval) {
2152 			if (rval == EACCES) {
2153 				un->un_dp->type = ST_TYPE_INVALID;
2154 				rval = 1;
2155 			} else {
2156 				rval = 0;
2157 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2158 				    "st_get_conf_from_tape_drive(): "
2159 				    "Fixed record size is too large and"
2160 				    "cannot switch to variable record size");
2161 			}
2162 			goto exit;
2163 		}
2164 		tem_dp->options |= ST_VARIABLE;
2165 	} else {
2166 		rval = st_change_block_size(un->un_dev, 0);
2167 		if (rval == 0) {
2168 			tem_dp->options |= ST_VARIABLE;
2169 			tem_dp->bsize = 0;
2170 		} else if (rval != EACCES) {
2171 			tem_dp->bsize = bsize;
2172 		} else {
2173 			un->un_dp->type = ST_TYPE_INVALID;
2174 			rval = 1;
2175 			goto exit;
2176 		}
2177 	}
2178 
2179 	/*
2180 	 * If READ BLOCk LIMITS works and upper block size limit is
2181 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2182 	 */
2183 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2184 	rval = st_read_block_limits(un, blklim);
2185 	if (rval) {
2186 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2187 		    "st_get_conf_from_tape_drive(): "
2188 		    "fail to read block limits.\n");
2189 		rval = 0;
2190 		kmem_free(blklim, sizeof (struct read_blklim));
2191 		goto exit;
2192 	}
2193 	maxbsize = (blklim->max_hi << 16) +
2194 	    (blklim->max_mid << 8) + blklim->max_lo;
2195 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2196 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2197 	}
2198 	kmem_free(blklim, sizeof (struct read_blklim));
2199 
2200 	/*
2201 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2202 	 */
2203 	buf = kmem_zalloc(6, KM_SLEEP);
2204 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2205 	if (rval) {
2206 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2207 		    "st_get_conf_from_tape_drive(): "
2208 		    "fail to read vitial inquiry.\n");
2209 		rval = 0;
2210 		kmem_free(buf, 6);
2211 		goto exit;
2212 	}
2213 	if (buf[4] & 1) {
2214 		tem_dp->options |= ST_WORMABLE;
2215 	}
2216 	kmem_free(buf, 6);
2217 
2218 	/* Assume BSD BSR KNOWS_EOD */
2219 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2220 	tem_dp->max_rretries = -1;
2221 	tem_dp->max_wretries = -1;
2222 
2223 	/*
2224 	 * Decide the densities supported by tape drive by sending
2225 	 * REPORT DENSITY SUPPORT command.
2226 	 */
2227 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2228 		goto exit;
2229 	}
2230 
2231 	/*
2232 	 * Decide the timeout values for several commands by sending
2233 	 * REPORT SUPPORTED OPERATION CODES command.
2234 	 */
2235 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2236 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2237 		goto exit;
2238 	}
2239 
2240 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2241 	rval = 1;
2242 
2243 exit:
2244 	un->un_status = KEY_NO_SENSE;
2245 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2246 	return (rval);
2247 }
2248 
2249 static int
2250 st_get_densities_from_tape_drive(struct scsi_tape *un,
2251     struct st_drivetype *dp)
2252 {
2253 	int i, p;
2254 	size_t buflen;
2255 	ushort_t des_len;
2256 	uchar_t *den_header;
2257 	uchar_t num_den;
2258 	uchar_t den[NDENSITIES];
2259 	uchar_t deflt[NDENSITIES];
2260 	struct report_density_desc *den_desc;
2261 
2262 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2263 
2264 	/*
2265 	 * Since we have no idea how many densitiy support entries
2266 	 * will be returned, we send the command firstly assuming
2267 	 * there is only one. Then we can decide the number of
2268 	 * entries by available density support length. If multiple
2269 	 * entries exist, we will resend the command with enough
2270 	 * buffer size.
2271 	 */
2272 	buflen = sizeof (struct report_density_header) +
2273 	    sizeof (struct report_density_desc);
2274 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2275 	if (st_report_density_support(un, den_header, buflen) != 0) {
2276 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2277 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2278 		kmem_free(den_header, buflen);
2279 		return (0);
2280 	}
2281 	des_len =
2282 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2283 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2284 
2285 	if (num_den > 1) {
2286 		kmem_free(den_header, buflen);
2287 		buflen = sizeof (struct report_density_header) +
2288 		    sizeof (struct report_density_desc) * num_den;
2289 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2290 		if (st_report_density_support(un, den_header, buflen) != 0) {
2291 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2292 			    "st_get_conf_from_tape_drive(): "
2293 			    "fail to report density.\n");
2294 			kmem_free(den_header, buflen);
2295 			return (0);
2296 		}
2297 	}
2298 
2299 	den_desc = (struct report_density_desc *)(den_header
2300 	    + sizeof (struct report_density_header));
2301 
2302 	/*
2303 	 * Decide the drive type by assigning organization
2304 	 */
2305 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2306 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2307 		    8) == 0) {
2308 			dp->type = st_vid_dt[i].type;
2309 			break;
2310 		}
2311 	}
2312 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2313 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2314 		    "st_get_conf_from_tape_drive(): "
2315 		    "can't find match of assigned ort.\n");
2316 		kmem_free(den_header, buflen);
2317 		return (0);
2318 	}
2319 
2320 	/*
2321 	 * The tape drive may support many tape formats, but the st driver
2322 	 * supports only the four highest densities. Since density code
2323 	 * values are returned by ascending sequence, we start from the
2324 	 * last entry of density support data block descriptor.
2325 	 */
2326 	p = 0;
2327 	den_desc += num_den - 1;
2328 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2329 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2330 			if (p != 0) {
2331 				if (den_desc->pri_den >= den[p - 1]) {
2332 					continue;
2333 				}
2334 			}
2335 			den[p] = den_desc->pri_den;
2336 			deflt[p] = den_desc->deflt;
2337 			p ++;
2338 		}
2339 	}
2340 
2341 	switch (p) {
2342 	case 0:
2343 		bzero(dp->densities, NDENSITIES);
2344 		dp->options |= ST_AUTODEN_OVERRIDE;
2345 		dp->default_density = MT_DENSITY4;
2346 		break;
2347 
2348 	case 1:
2349 		(void) memset(dp->densities, den[0], NDENSITIES);
2350 		dp->options |= ST_AUTODEN_OVERRIDE;
2351 		dp->default_density = MT_DENSITY4;
2352 		break;
2353 
2354 	case 2:
2355 		dp->densities[0] = den[1];
2356 		dp->densities[1] = den[1];
2357 		dp->densities[2] = den[0];
2358 		dp->densities[3] = den[0];
2359 		if (deflt[0]) {
2360 			dp->default_density = MT_DENSITY4;
2361 		} else {
2362 			dp->default_density = MT_DENSITY2;
2363 		}
2364 		break;
2365 
2366 	case 3:
2367 		dp->densities[0] = den[2];
2368 		dp->densities[1] = den[1];
2369 		dp->densities[2] = den[0];
2370 		dp->densities[3] = den[0];
2371 		if (deflt[0]) {
2372 			dp->default_density = MT_DENSITY4;
2373 		} else if (deflt[1]) {
2374 			dp->default_density = MT_DENSITY2;
2375 		} else {
2376 			dp->default_density = MT_DENSITY1;
2377 		}
2378 		break;
2379 
2380 	default:
2381 		for (i = p; i > p - NDENSITIES; i --) {
2382 			dp->densities[i - 1] = den[p - i];
2383 		}
2384 		if (deflt[0]) {
2385 			dp->default_density = MT_DENSITY4;
2386 		} else if (deflt[1]) {
2387 			dp->default_density = MT_DENSITY3;
2388 		} else if (deflt[2]) {
2389 			dp->default_density = MT_DENSITY2;
2390 		} else {
2391 			dp->default_density = MT_DENSITY1;
2392 		}
2393 		break;
2394 	}
2395 
2396 	bzero(dp->mediatype, NDENSITIES);
2397 
2398 	kmem_free(den_header, buflen);
2399 	return (1);
2400 }
2401 
2402 static int
2403 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2404     struct st_drivetype *dp)
2405 {
2406 	ushort_t timeout;
2407 	int rval;
2408 
2409 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2410 
2411 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2412 	if (rval) {
2413 		if (rval == EACCES) {
2414 			un->un_dp->type = ST_TYPE_INVALID;
2415 			dp->type = ST_TYPE_INVALID;
2416 			return (1);
2417 		}
2418 		return (0);
2419 	}
2420 	dp->erase_timeout = timeout;
2421 
2422 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2423 	if (rval) {
2424 		if (rval == EACCES) {
2425 			un->un_dp->type = ST_TYPE_INVALID;
2426 			dp->type = ST_TYPE_INVALID;
2427 			return (1);
2428 		}
2429 		return (0);
2430 	}
2431 	dp->io_timeout = timeout;
2432 
2433 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2434 	if (rval) {
2435 		if (rval == EACCES) {
2436 			un->un_dp->type = ST_TYPE_INVALID;
2437 			dp->type = ST_TYPE_INVALID;
2438 			return (1);
2439 		}
2440 		return (0);
2441 	}
2442 	dp->io_timeout = max(dp->io_timeout, timeout);
2443 
2444 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2445 	if (rval) {
2446 		if (rval == EACCES) {
2447 			un->un_dp->type = ST_TYPE_INVALID;
2448 			dp->type = ST_TYPE_INVALID;
2449 			return (1);
2450 		}
2451 		return (0);
2452 	}
2453 	dp->space_timeout = timeout;
2454 
2455 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2456 	if (rval) {
2457 		if (rval == EACCES) {
2458 			un->un_dp->type = ST_TYPE_INVALID;
2459 			dp->type = ST_TYPE_INVALID;
2460 			return (1);
2461 		}
2462 		return (0);
2463 	}
2464 	dp->load_timeout = timeout;
2465 	dp->unload_timeout = timeout;
2466 
2467 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2468 	if (rval) {
2469 		if (rval == EACCES) {
2470 			un->un_dp->type = ST_TYPE_INVALID;
2471 			dp->type = ST_TYPE_INVALID;
2472 			return (1);
2473 		}
2474 		return (0);
2475 	}
2476 	dp->rewind_timeout = timeout;
2477 
2478 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2479 	if (rval) {
2480 		if (rval == EACCES) {
2481 			un->un_dp->type = ST_TYPE_INVALID;
2482 			dp->type = ST_TYPE_INVALID;
2483 			return (1);
2484 		}
2485 		return (0);
2486 	}
2487 	dp->non_motion_timeout = timeout;
2488 
2489 	return (1);
2490 }
2491 
2492 static int
2493 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2494     ushort_t *timeout_value, ushort_t service_action)
2495 {
2496 	uchar_t *timeouts;
2497 	uchar_t *oper;
2498 	uchar_t support;
2499 	uchar_t cdbsize;
2500 	uchar_t ctdp;
2501 	size_t buflen;
2502 	int rval;
2503 
2504 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2505 
2506 	buflen = sizeof (struct one_com_des) +
2507 	    sizeof (struct com_timeout_des);
2508 	oper = kmem_zalloc(buflen, KM_SLEEP);
2509 	rval = st_report_supported_operation(un, oper, option_code,
2510 	    service_action);
2511 
2512 	if (rval) {
2513 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2514 		    "st_get_timeouts_value(): "
2515 		    "fail to timeouts value for command %d.\n", option_code);
2516 		kmem_free(oper, buflen);
2517 		return (rval);
2518 	}
2519 
2520 	support = ((struct one_com_des *)oper)->support;
2521 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2522 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2523 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2524 		    "st_get_timeouts_value(): "
2525 		    "command %d is not supported.\n", option_code);
2526 		kmem_free(oper, buflen);
2527 		return (ENOTSUP);
2528 	}
2529 
2530 	ctdp = ((struct one_com_des *)oper)->ctdp;
2531 	if (!ctdp) {
2532 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2533 		    "st_get_timeouts_value(): "
2534 		    "command timeout is not included.\n");
2535 		kmem_free(oper, buflen);
2536 		return (ENOTSUP);
2537 	}
2538 
2539 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2540 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2541 
2542 	/*
2543 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2544 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2545 	 * to 0xFFFF.
2546 	 */
2547 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2548 		*timeout_value = USHRT_MAX;
2549 	} else {
2550 		*timeout_value = ((*(timeouts + 10)) << 8) |
2551 		    (*(timeouts + 11));
2552 	}
2553 
2554 	kmem_free(oper, buflen);
2555 	return (0);
2556 }
2557 
2558 static int
2559 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2560 {
2561 	int i;
2562 
2563 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2564 
2565 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2566 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2567 
2568 	/*
2569 	 * Make up a name
2570 	 */
2571 	bcopy("Vendor '", dp->name, 8);
2572 	bcopy(vidpid, &dp->name[8], VIDLEN);
2573 	bcopy("' Product '", &dp->name[16], 11);
2574 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2575 	dp->name[ST_NAMESIZE - 2] = '\'';
2576 	dp->name[ST_NAMESIZE - 1] = '\0';
2577 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2578 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2579 	/*
2580 	 * 'clean' vendor and product strings of non-printing chars
2581 	 */
2582 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2583 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2584 			dp->name[i] = '.';
2585 		}
2586 	}
2587 	dp->type = ST_TYPE_INVALID;
2588 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2589 
2590 	return (1); /* Can Not Fail */
2591 }
2592 
2593 /*
2594  * Regular Unix Entry points
2595  */
2596 
2597 
2598 
2599 /* ARGSUSED */
2600 static int
2601 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2602 {
2603 	dev_t dev = *dev_p;
2604 	int rval = 0;
2605 
2606 	GET_SOFT_STATE(dev);
2607 
2608 	ST_ENTR(ST_DEVINFO, st_open);
2609 
2610 	/*
2611 	 * validate that we are addressing a sensible unit
2612 	 */
2613 	mutex_enter(ST_MUTEX);
2614 
2615 #ifdef	STDEBUG
2616 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2617 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2618 	    st_dev_name(dev), *dev_p, flag, otyp);
2619 #endif
2620 
2621 	/*
2622 	 * All device accesss go thru st_strategy() where we check
2623 	 * suspend status
2624 	 */
2625 
2626 	if (!un->un_attached) {
2627 		st_known_tape_type(un);
2628 		if (!un->un_attached) {
2629 			rval = ENXIO;
2630 			goto exit;
2631 		}
2632 
2633 	}
2634 
2635 	/*
2636 	 * Check for the case of the tape in the middle of closing.
2637 	 * This isn't simply a check of the current state, because
2638 	 * we could be in state of sensing with the previous state
2639 	 * that of closing.
2640 	 *
2641 	 * And don't allow multiple opens.
2642 	 */
2643 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2644 		un->un_laststate = un->un_state;
2645 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2646 		while (IS_CLOSING(un) ||
2647 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2648 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2649 				rval = EINTR;
2650 				un->un_state = un->un_laststate;
2651 				goto exit;
2652 			}
2653 		}
2654 	} else if (un->un_state != ST_STATE_CLOSED) {
2655 		rval = EBUSY;
2656 		goto busy;
2657 	}
2658 
2659 	/*
2660 	 * record current dev
2661 	 */
2662 	un->un_dev = dev;
2663 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2664 	un->un_errno = 0;	/* no errors yet */
2665 	un->un_restore_pos = 0;
2666 	un->un_rqs_state = 0;
2667 
2668 	/*
2669 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2670 	 * anything, leave internal states alone, if fileno >= 0
2671 	 */
2672 	if (flag & (FNDELAY | FNONBLOCK)) {
2673 		switch (un->un_pos.pmode) {
2674 
2675 		case invalid:
2676 			un->un_state = ST_STATE_OFFLINE;
2677 			break;
2678 
2679 		case legacy:
2680 			/*
2681 			 * If position is anything other than rewound.
2682 			 */
2683 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2684 				/*
2685 				 * set un_read_only/write-protect status.
2686 				 *
2687 				 * If the tape is not bot we can assume
2688 				 * that mspl->wp_status is set properly.
2689 				 * else
2690 				 * we need to do a mode sense/Tur once
2691 				 * again to get the actual tape status.(since
2692 				 * user might have replaced the tape)
2693 				 * Hence make the st state OFFLINE so that
2694 				 * we re-intialize the tape once again.
2695 				 */
2696 				un->un_read_only =
2697 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2698 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2699 			} else {
2700 				un->un_state = ST_STATE_OFFLINE;
2701 			}
2702 			break;
2703 		case logical:
2704 			/* swag not sure how we were open last time */
2705 			(void) st_update_block_pos(un);
2706 			if (un->un_pos.lgclblkno == 0) {
2707 				un->un_state = ST_STATE_OFFLINE;
2708 			} else {
2709 				un->un_read_only =
2710 				    (un->un_oflags & FWRITE) ? 0 : 1;
2711 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2712 			}
2713 			break;
2714 		}
2715 		rval = 0;
2716 	} else {
2717 		/*
2718 		 * Not opening O_NDELAY.
2719 		 */
2720 		un->un_state = ST_STATE_OPENING;
2721 
2722 		/*
2723 		 * Clear error entry stack
2724 		 */
2725 		st_empty_error_stack(un);
2726 
2727 		rval = st_tape_init(dev);
2728 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2729 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2730 			rval = 0; /* so open doesn't fail */
2731 		} else if (rval) {
2732 			/*
2733 			 * Release the tape unit, if reserved and not
2734 			 * preserve reserve.
2735 			 */
2736 			if ((un->un_rsvd_status &
2737 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2738 				(void) st_reserve_release(un, ST_RELEASE);
2739 			}
2740 		} else {
2741 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2742 		}
2743 	}
2744 
2745 exit:
2746 	/*
2747 	 * we don't want any uninvited guests scrogging our data when we're
2748 	 * busy with something, so for successful opens or failed opens
2749 	 * (except for EBUSY), reset these counters and state appropriately.
2750 	 */
2751 	if (rval != EBUSY) {
2752 		if (rval) {
2753 			un->un_state = ST_STATE_CLOSED;
2754 		}
2755 		un->un_err_resid = 0;
2756 		un->un_retry_ct = 0;
2757 		un->un_tran_retry_ct = 0;
2758 	}
2759 busy:
2760 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2761 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2762 	mutex_exit(ST_MUTEX);
2763 	return (rval);
2764 
2765 }
2766 
2767 static int
2768 st_tape_init(dev_t dev)
2769 {
2770 	int err;
2771 	int rval = 0;
2772 
2773 	GET_SOFT_STATE(dev);
2774 
2775 	ST_FUNC(ST_DEVINFO, st_tape_init);
2776 
2777 	ASSERT(mutex_owned(ST_MUTEX));
2778 
2779 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2780 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2781 
2782 	/*
2783 	 * Clean up after any errors left by 'last' close.
2784 	 * This also handles the case of the initial open.
2785 	 */
2786 	if (un->un_state != ST_STATE_INITIALIZING) {
2787 		un->un_laststate = un->un_state;
2788 		un->un_state = ST_STATE_OPENING;
2789 	}
2790 
2791 	un->un_kbytes_xferred = 0;
2792 
2793 	/*
2794 	 * do a throw away TUR to clear check condition
2795 	 */
2796 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2797 
2798 	/*
2799 	 * If test unit ready fails because the drive is reserved
2800 	 * by another host fail the open for no access.
2801 	 */
2802 	if (err) {
2803 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2804 			un->un_state = ST_STATE_CLOSED;
2805 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2806 			    "st_tape_init: RESERVATION CONFLICT\n");
2807 			rval = EACCES;
2808 			goto exit;
2809 		}
2810 	}
2811 
2812 	/*
2813 	 * Tape self identification could fail if the tape drive is used by
2814 	 * another host during attach time. We try to get the tape type
2815 	 * again. This is also applied to any posponed configuration methods.
2816 	 */
2817 	if (un->un_dp->type == ST_TYPE_INVALID) {
2818 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2819 		st_known_tape_type(un);
2820 	}
2821 
2822 	/*
2823 	 * If the tape type is still invalid, try to determine the generic
2824 	 * configuration.
2825 	 */
2826 	if (un->un_dp->type == ST_TYPE_INVALID) {
2827 		rval = st_determine_generic(dev);
2828 		if (rval) {
2829 			if (rval != EACCES) {
2830 				rval = EIO;
2831 			}
2832 			un->un_state = ST_STATE_CLOSED;
2833 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2834 			    "st_tape_init: %s invalid type\n",
2835 			    rval == EACCES ? "EACCES" : "EIO");
2836 			goto exit;
2837 		}
2838 		/*
2839 		 * If this is a Unknown Type drive,
2840 		 * Use the READ BLOCK LIMITS to determine if
2841 		 * allow large xfer is approprate if not globally
2842 		 * disabled with st_allow_large_xfer.
2843 		 */
2844 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2845 	} else {
2846 
2847 		/*
2848 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2849 		 * the max block size supported by the drive,
2850 		 * find it by issueing a READ_BLKLIM command.
2851 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2852 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2853 		 */
2854 		un->un_allow_large_xfer = st_allow_large_xfer &&
2855 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2856 	}
2857 	/*
2858 	 * if maxbsize is unknown, set the maximum block size.
2859 	 */
2860 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2861 
2862 		/*
2863 		 * Get the Block limits of the tape drive.
2864 		 * if un->un_allow_large_xfer = 0 , then make sure
2865 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2866 		 */
2867 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2868 
2869 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2870 		if (err) {
2871 			/* Retry */
2872 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2873 		}
2874 		if (!err) {
2875 
2876 			/*
2877 			 * if cmd successful, use limit returned
2878 			 */
2879 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2880 			    (un->un_rbl->max_mid << 8) +
2881 			    un->un_rbl->max_lo;
2882 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2883 			    un->un_rbl->min_lo;
2884 			un->un_data_mod = 1 << un->un_rbl->granularity;
2885 			if ((un->un_maxbsize == 0) ||
2886 			    (un->un_allow_large_xfer == 0 &&
2887 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2888 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2889 
2890 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2891 				/*
2892 				 * Drive is not one that is configured, But the
2893 				 * READ BLOCK LIMITS tells us it can do large
2894 				 * xfers.
2895 				 */
2896 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2897 					un->un_dp->options |=
2898 					    ST_NO_RECSIZE_LIMIT;
2899 				}
2900 				/*
2901 				 * If max and mimimum block limits are the
2902 				 * same this is a fixed block size device.
2903 				 */
2904 				if (un->un_maxbsize == un->un_minbsize) {
2905 					un->un_dp->options &= ~ST_VARIABLE;
2906 				}
2907 			}
2908 
2909 			if (un->un_minbsize == 0) {
2910 				un->un_minbsize = 1;
2911 			}
2912 
2913 		} else { /* error on read block limits */
2914 
2915 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2916 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
2917 			    " errno = %d un_rsvd_status = 0x%X\n",
2918 			    err, un->un_rsvd_status);
2919 
2920 			/*
2921 			 * since read block limits cmd failed,
2922 			 * do not allow large xfers.
2923 			 * use old values in st_minphys
2924 			 */
2925 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2926 				rval = EACCES;
2927 			} else {
2928 				un->un_allow_large_xfer = 0;
2929 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2930 				    "!Disabling large transfers\n");
2931 
2932 				/*
2933 				 * we guess maxbsize and minbsize
2934 				 */
2935 				if (un->un_bsize) {
2936 					un->un_maxbsize = un->un_minbsize =
2937 					    un->un_bsize;
2938 				} else {
2939 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2940 					un->un_minbsize = 1;
2941 				}
2942 				/*
2943 				 * Data Mod must be set,
2944 				 * Even if read block limits fails.
2945 				 * Prevents Divide By Zero in st_rw().
2946 				 */
2947 				un->un_data_mod = 1;
2948 			}
2949 		}
2950 		if (un->un_rbl) {
2951 			kmem_free(un->un_rbl, RBLSIZE);
2952 			un->un_rbl = NULL;
2953 		}
2954 
2955 		if (rval) {
2956 			goto exit;
2957 		}
2958 	}
2959 
2960 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2961 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2962 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2963 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2964 
2965 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2966 
2967 	if (err != 0) {
2968 		if (err == EINTR) {
2969 			un->un_laststate = un->un_state;
2970 			un->un_state = ST_STATE_CLOSED;
2971 			rval = EINTR;
2972 			goto exit;
2973 		}
2974 		/*
2975 		 * Make sure the tape is ready
2976 		 */
2977 		un->un_pos.pmode = invalid;
2978 		if (un->un_status != KEY_UNIT_ATTENTION) {
2979 			/*
2980 			 * allow open no media.  Subsequent MTIOCSTATE
2981 			 * with media present will complete the open
2982 			 * logic.
2983 			 */
2984 			un->un_laststate = un->un_state;
2985 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2986 				un->un_mediastate = MTIO_EJECTED;
2987 				un->un_state = ST_STATE_OFFLINE;
2988 				rval = 0;
2989 				goto exit;
2990 			} else {
2991 				un->un_state = ST_STATE_CLOSED;
2992 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2993 				    "st_tape_init EIO no media, not opened "
2994 				    "O_NONBLOCK|O_EXCL\n");
2995 				rval = EIO;
2996 				goto exit;
2997 			}
2998 		}
2999 	}
3000 
3001 	/*
3002 	 * On each open, initialize block size from drivetype struct,
3003 	 * as it could have been changed by MTSRSZ ioctl.
3004 	 * Now, ST_VARIABLE simply means drive is capable of variable
3005 	 * mode. All drives are assumed to support fixed records.
3006 	 * Hence, un_bsize tells what mode the drive is in.
3007 	 *	un_bsize	= 0	- variable record length
3008 	 *			= x	- fixed record length is x
3009 	 */
3010 	un->un_bsize = un->un_dp->bsize;
3011 
3012 	/*
3013 	 * If saved position is valid go there
3014 	 */
3015 	if (un->un_restore_pos) {
3016 		rval = st_validate_tapemarks(un, &un->un_pos);
3017 		if (rval != 0) {
3018 			if (rval != EACCES) {
3019 				rval = EIO;
3020 			}
3021 			un->un_restore_pos = 0;
3022 			un->un_laststate = un->un_state;
3023 			un->un_state = ST_STATE_CLOSED;
3024 			goto exit;
3025 		}
3026 		un->un_pos.fileno = un->un_save_fileno;
3027 		un->un_pos.blkno = un->un_save_blkno;
3028 		un->un_restore_pos = 0;
3029 	}
3030 
3031 	if (un->un_pos.pmode == invalid) {
3032 		rval = st_loadtape(dev);
3033 		if (rval) {
3034 			if (rval != EACCES) {
3035 				rval = EIO;
3036 			}
3037 			un->un_laststate = un->un_state;
3038 			un->un_state = ST_STATE_CLOSED;
3039 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3040 			    "st_tape_init: %s can't open tape\n",
3041 			    rval == EACCES ? "EACCES" : "EIO");
3042 			goto exit;
3043 		}
3044 	}
3045 
3046 	/*
3047 	 * do a mode sense to pick up state of current write-protect,
3048 	 * Could cause reserve and fail due to conflict.
3049 	 */
3050 	rval = st_modesense(un);
3051 	if (rval == EACCES) {
3052 		goto exit;
3053 	}
3054 
3055 	/*
3056 	 * If we are opening the tape for writing, check
3057 	 * to make sure that the tape can be written.
3058 	 */
3059 	if (un->un_oflags & FWRITE) {
3060 		err = 0;
3061 		if (un->un_mspl->wp) {
3062 			un->un_status = KEY_WRITE_PROTECT;
3063 			un->un_laststate = un->un_state;
3064 			un->un_state = ST_STATE_CLOSED;
3065 			rval = EACCES;
3066 			/*
3067 			 * STK sets the wp bit if volsafe tape is loaded.
3068 			 */
3069 			if ((un->un_dp->type == MT_ISSTK9840) &&
3070 			    (un->un_dp->options & ST_WORMABLE)) {
3071 				un->un_read_only = RDONLY;
3072 			} else {
3073 				goto exit;
3074 			}
3075 		} else {
3076 			un->un_read_only = RDWR;
3077 		}
3078 	} else {
3079 		un->un_read_only = RDONLY;
3080 	}
3081 
3082 	if (un->un_dp->options & ST_WORMABLE) {
3083 		un->un_read_only |= un->un_wormable(un);
3084 
3085 		if (((un->un_read_only == WORM) ||
3086 		    (un->un_read_only == RDWORM)) &&
3087 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3088 			un->un_status = KEY_DATA_PROTECT;
3089 			rval = EACCES;
3090 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3091 			    "read_only = %d eof = %d oflag = %d\n",
3092 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3093 		}
3094 	}
3095 
3096 	/*
3097 	 * If we're opening the tape write-only, we need to
3098 	 * write 2 filemarks on the HP 1/2 inch drive, to
3099 	 * create a null file.
3100 	 */
3101 	if ((un->un_read_only == RDWR) ||
3102 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3103 		if (un->un_dp->options & ST_REEL) {
3104 			un->un_fmneeded = 2;
3105 		} else {
3106 			un->un_fmneeded = 1;
3107 		}
3108 	} else {
3109 		un->un_fmneeded = 0;
3110 	}
3111 
3112 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3113 	    "fmneeded = %x\n", un->un_fmneeded);
3114 
3115 	/*
3116 	 * Make sure the density can be selected correctly.
3117 	 * If WORM can only write at the append point which in most cases
3118 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3119 	 * to set and try densities if a BOP.
3120 	 */
3121 	if (st_determine_density(dev,
3122 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3123 		un->un_status = KEY_ILLEGAL_REQUEST;
3124 		un->un_laststate = un->un_state;
3125 		un->un_state = ST_STATE_CLOSED;
3126 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3127 		    "st_tape_init: EIO can't determine density\n");
3128 		rval = EIO;
3129 		goto exit;
3130 	}
3131 
3132 	/*
3133 	 * Destroy the knowledge that we have 'determined'
3134 	 * density so that a later read at BOT comes along
3135 	 * does the right density determination.
3136 	 */
3137 
3138 	un->un_density_known = 0;
3139 
3140 
3141 	/*
3142 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3143 	 * Mark the state such that any I/O or tape space operations
3144 	 * will get/set the right density, etc..
3145 	 */
3146 	un->un_laststate = un->un_state;
3147 	un->un_lastop = ST_OP_NIL;
3148 	un->un_mediastate = MTIO_INSERTED;
3149 	cv_broadcast(&un->un_state_cv);
3150 
3151 	/*
3152 	 *  Set test append flag if writing.
3153 	 *  First write must check that tape is positioned correctly.
3154 	 */
3155 	un->un_test_append = (un->un_oflags & FWRITE);
3156 
3157 exit:
3158 	un->un_err_resid = 0;
3159 	un->un_last_resid = 0;
3160 	un->un_last_count = 0;
3161 
3162 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3163 	    "st_tape_init: return val = %x\n", rval);
3164 	return (rval);
3165 
3166 }
3167 
3168 
3169 
3170 /* ARGSUSED */
3171 static int
3172 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3173 {
3174 	int err = 0;
3175 	int norew, count, last_state;
3176 #ifdef	__x86
3177 	struct contig_mem *cp, *cp_temp;
3178 #endif
3179 
3180 	GET_SOFT_STATE(dev);
3181 
3182 	ST_ENTR(ST_DEVINFO, st_close);
3183 
3184 	/*
3185 	 * wait till all cmds in the pipeline have been completed
3186 	 */
3187 	mutex_enter(ST_MUTEX);
3188 
3189 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3190 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3191 
3192 	st_wait_for_io(un);
3193 
3194 	/* turn off persistent errors on close, as we want close to succeed */
3195 	TURN_PE_OFF(un);
3196 
3197 	/*
3198 	 * set state to indicate that we are in process of closing
3199 	 */
3200 	last_state = un->un_laststate = un->un_state;
3201 	un->un_state = ST_STATE_CLOSING;
3202 
3203 	/*
3204 	 * BSD behavior:
3205 	 * a close always causes a silent span to the next file if we've hit
3206 	 * an EOF (but not yet read across it).
3207 	 */
3208 #ifdef DEBUG
3209 	if ((st_debug & 0xf) >= 6)
3210 		st_print_position(un, "st_close1:", &un->un_pos);
3211 #endif
3212 
3213 	if (BSD_BEHAVIOR && (un->un_pos.eof == ST_EOF)) {
3214 		if (un->un_pos.pmode != invalid) {
3215 			un->un_pos.fileno++;
3216 			un->un_pos.blkno = 0;
3217 		}
3218 		un->un_pos.eof = ST_NO_EOF;
3219 	}
3220 
3221 	/*
3222 	 * rewinding?
3223 	 */
3224 	norew = (getminor(dev) & MT_NOREWIND);
3225 
3226 	/*
3227 	 * SVR4 behavior for skipping to next file:
3228 	 *
3229 	 * If we have not seen a filemark, space to the next file
3230 	 *
3231 	 * If we have already seen the filemark we are physically in the next
3232 	 * file and we only increment the filenumber
3233 	 */
3234 
3235 
3236 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) &&
3237 	    (un->un_pos.blkno != 0) &&
3238 	    ((un->un_lastop != ST_OP_WRITE) && (un->un_lastop != ST_OP_WEOF))) {
3239 		switch (un->un_pos.eof) {
3240 		case ST_NO_EOF:
3241 			/*
3242 			 * if we were reading and did not read the complete file
3243 			 * skip to the next file, leaving the tape correctly
3244 			 * positioned to read the first record of the next file
3245 			 * Check first for REEL if we are at EOT by trying to
3246 			 * read a block
3247 			 */
3248 			if ((un->un_dp->options & ST_REEL) &&
3249 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3250 			    (un->un_pos.blkno == 0)) {
3251 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3252 					ST_DEBUG2(ST_DEVINFO, st_label,
3253 					    SCSI_DEBUG,
3254 					    "st_close : EIO can't space\n");
3255 					err = EIO;
3256 					break;
3257 				}
3258 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3259 					un->un_pos.eof = ST_EOT_PENDING;
3260 					un->un_pos.fileno += 1;
3261 					un->un_pos.blkno   = 0;
3262 					break;
3263 				}
3264 			}
3265 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3266 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3267 				    "st_close: EIO can't space #2\n");
3268 				err = EIO;
3269 			} else {
3270 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3271 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3272 				    un->un_pos.fileno, un->un_pos.blkno,
3273 				    un->un_pos.eof);
3274 				un->un_pos.eof = ST_NO_EOF;
3275 			}
3276 			break;
3277 
3278 		case ST_EOF_PENDING:
3279 		case ST_EOF:
3280 			un->un_pos.fileno += 1;
3281 			un->un_pos.blkno   = 0;
3282 			un->un_pos.eof = ST_NO_EOF;
3283 			break;
3284 
3285 		case ST_EOT:
3286 		case ST_EOT_PENDING:
3287 			/* nothing to do */
3288 			break;
3289 		default:
3290 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
3291 			    "Undefined state 0x%x", un->un_pos.eof);
3292 
3293 		}
3294 	}
3295 
3296 
3297 	/*
3298 	 * For performance reasons (HP 88780), the driver should
3299 	 * postpone writing the second tape mark until just before a file
3300 	 * positioning ioctl is issued (e.g., rewind).	This means that
3301 	 * the user must not manually rewind the tape because the tape will
3302 	 * be missing the second tape mark which marks EOM.
3303 	 * However, this small performance improvement is not worth the risk.
3304 	 */
3305 
3306 	/*
3307 	 * We need to back up over the filemark we inadvertently popped
3308 	 * over doing a read in between the two filemarks that constitute
3309 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3310 	 * set while reading.
3311 	 *
3312 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3313 	 * the writing of filemark(s) will clear the ST_EOM state, which
3314 	 * we don't want, so we save this state and restore it later.
3315 	 */
3316 
3317 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3318 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3319 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3320 
3321 	if (un->un_pos.eof == ST_EOT_PENDING) {
3322 		if (norew) {
3323 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3324 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3325 				    "st_close: EIO can't space #3\n");
3326 				err = EIO;
3327 			} else {
3328 				un->un_pos.blkno = 0;
3329 				un->un_pos.eof = ST_EOT;
3330 			}
3331 		} else {
3332 			un->un_pos.eof = ST_NO_EOF;
3333 		}
3334 
3335 	/*
3336 	 * Do we need to write a file mark?
3337 	 *
3338 	 * only write filemarks if there are fmks to be written and
3339 	 *   - open for write (possibly read/write)
3340 	 *   - the last operation was a write
3341 	 * or:
3342 	 *   -	opened for wronly
3343 	 *   -	no data was written
3344 	 */
3345 	} else if ((un->un_pos.pmode != invalid) && (un->un_fmneeded > 0) &&
3346 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
3347 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
3348 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3349 
3350 		/* save ST_EOM state */
3351 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3352 
3353 		/*
3354 		 * Note that we will write a filemark if we had opened
3355 		 * the tape write only and no data was written, thus
3356 		 * creating a null file.
3357 		 *
3358 		 * If the user already wrote one, we only have to write 1 more.
3359 		 * If they wrote two, we don't have to write any.
3360 		 */
3361 
3362 		count = un->un_fmneeded;
3363 		if (count > 0) {
3364 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
3365 			    count, SYNC_CMD)) {
3366 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3367 				    "st_close : EIO can't wfm\n");
3368 				err = EIO;
3369 			}
3370 			if ((un->un_dp->options & ST_REEL) && norew) {
3371 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
3372 				    SYNC_CMD)) {
3373 					ST_DEBUG2(ST_DEVINFO, st_label,
3374 					    SCSI_DEBUG,
3375 					    "st_close : EIO space fmk(-1)\n");
3376 					err = EIO;
3377 				}
3378 				un->un_pos.eof = ST_NO_EOF;
3379 				/* fix up block number */
3380 				un->un_pos.blkno = 0;
3381 			}
3382 		}
3383 
3384 		/*
3385 		 * If we aren't going to be rewinding, and we were at
3386 		 * physical eot, restore the state that indicates we
3387 		 * are at physical eot. Once you have reached physical
3388 		 * eot, and you close the tape, the only thing you can
3389 		 * do on the next open is to rewind. Access to trailer
3390 		 * records is only allowed without closing the device.
3391 		 */
3392 		if (norew == 0 && was_at_eom) {
3393 			un->un_pos.eof = ST_EOM;
3394 		}
3395 	}
3396 
3397 	/*
3398 	 * report soft errors if enabled and available, if we never accessed
3399 	 * the drive, don't get errors. This will prevent some DAT error
3400 	 * messages upon LOG SENSE.
3401 	 */
3402 	if (st_report_soft_errors_on_close &&
3403 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3404 	    (last_state != ST_STATE_OFFLINE)) {
3405 		(void) st_report_soft_errors(dev, flag);
3406 	}
3407 
3408 
3409 	/*
3410 	 * Do we need to rewind? Can we rewind?
3411 	 */
3412 	if (norew == 0 && un->un_pos.pmode != invalid && err == 0) {
3413 		/*
3414 		 * We'd like to rewind with the
3415 		 * 'immediate' bit set, but this
3416 		 * causes problems on some drives
3417 		 * where subsequent opens get a
3418 		 * 'NOT READY' error condition
3419 		 * back while the tape is rewinding,
3420 		 * which is impossible to distinguish
3421 		 * from the condition of 'no tape loaded'.
3422 		 *
3423 		 * Also, for some targets, if you disconnect
3424 		 * with the 'immediate' bit set, you don't
3425 		 * actually return right away, i.e., the
3426 		 * target ignores your request for immediate
3427 		 * return.
3428 		 *
3429 		 * Instead, we'll fire off an async rewind
3430 		 * command. We'll mark the device as closed,
3431 		 * and any subsequent open will stall on
3432 		 * the first TEST_UNIT_READY until the rewind
3433 		 * completes.
3434 		 */
3435 
3436 		/*
3437 		 * Used to be if reserve was not supported we'd send an
3438 		 * asynchronious rewind. Comments above may be slightly invalid
3439 		 * as the immediate bit was never set. Doing an immedate rewind
3440 		 * makes sense, I think fixes to not ready status might handle
3441 		 * the problems described above.
3442 		 */
3443 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3444 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
3445 		} else {
3446 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
3447 		}
3448 	}
3449 
3450 	/*
3451 	 * eject tape if necessary
3452 	 */
3453 	if (un->un_eject_tape_on_failure) {
3454 		un->un_eject_tape_on_failure = 0;
3455 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3456 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3457 			    "st_close : can't unload tape\n");
3458 		} else {
3459 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3460 			    "st_close : tape unloaded \n");
3461 			un->un_pos.eof = ST_NO_EOF;
3462 			un->un_mediastate = MTIO_EJECTED;
3463 		}
3464 	}
3465 	/*
3466 	 * Release the tape unit, if default reserve/release
3467 	 * behaviour.
3468 	 */
3469 	if ((un->un_rsvd_status &
3470 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3471 		(void) st_reserve_release(un, ST_RELEASE);
3472 	}
3473 
3474 	/*
3475 	 * clear up state
3476 	 */
3477 	un->un_laststate = un->un_state;
3478 	un->un_state = ST_STATE_CLOSED;
3479 	un->un_lastop = ST_OP_NIL;
3480 	un->un_throttle = 1;	/* assume one request at time, for now */
3481 	un->un_retry_ct = 0;
3482 	un->un_tran_retry_ct = 0;
3483 	un->un_errno = 0;
3484 	un->un_swr_token = (opaque_t)NULL;
3485 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3486 
3487 	/* Restore the options to the init time settings */
3488 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3489 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3490 	} else {
3491 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3492 	}
3493 
3494 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3495 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3496 	} else {
3497 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3498 	}
3499 
3500 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3501 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3502 	} else {
3503 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3504 	}
3505 
3506 	ASSERT(mutex_owned(ST_MUTEX));
3507 
3508 	/*
3509 	 * Signal anyone awaiting a close operation to complete.
3510 	 */
3511 	cv_signal(&un->un_clscv);
3512 
3513 	/*
3514 	 * any kind of error on closing causes all state to be tossed
3515 	 */
3516 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3517 		/*
3518 		 * note that st_intr has already set
3519 		 * un_pos.pmode to invalid.
3520 		 */
3521 		un->un_density_known = 0;
3522 	}
3523 
3524 #ifdef	__x86
3525 	/*
3526 	 * free any contiguous mem alloc'ed for big block I/O
3527 	 */
3528 	cp = un->un_contig_mem;
3529 	while (cp) {
3530 		if (cp->cm_addr) {
3531 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3532 		}
3533 		cp_temp = cp;
3534 		cp = cp->cm_next;
3535 		kmem_free(cp_temp,
3536 		    sizeof (struct contig_mem) + biosize());
3537 	}
3538 	un->un_contig_mem_total_num = 0;
3539 	un->un_contig_mem_available_num = 0;
3540 	un->un_contig_mem = NULL;
3541 	un->un_max_contig_mem_len = 0;
3542 #endif
3543 
3544 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3545 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3546 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3547 
3548 	mutex_exit(ST_MUTEX);
3549 	return (err);
3550 }
3551 
3552 /*
3553  * These routines perform raw i/o operations.
3554  */
3555 
3556 /* ARGSUSED2 */
3557 static int
3558 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3559 {
3560 #ifdef DEBUG
3561 	GET_SOFT_STATE(dev);
3562 	ST_ENTR(ST_DEVINFO, st_aread);
3563 #endif
3564 	return (st_arw(dev, aio, B_READ));
3565 }
3566 
3567 
3568 /* ARGSUSED2 */
3569 static int
3570 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3571 {
3572 #ifdef DEBUG
3573 	GET_SOFT_STATE(dev);
3574 	ST_ENTR(ST_DEVINFO, st_awrite);
3575 #endif
3576 	return (st_arw(dev, aio, B_WRITE));
3577 }
3578 
3579 
3580 
3581 /* ARGSUSED */
3582 static int
3583 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3584 {
3585 #ifdef DEBUG
3586 	GET_SOFT_STATE(dev);
3587 	ST_ENTR(ST_DEVINFO, st_read);
3588 #endif
3589 	return (st_rw(dev, uiop, B_READ));
3590 }
3591 
3592 /* ARGSUSED */
3593 static int
3594 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3595 {
3596 #ifdef DEBUG
3597 	GET_SOFT_STATE(dev);
3598 	ST_ENTR(ST_DEVINFO, st_write);
3599 #endif
3600 	return (st_rw(dev, uiop, B_WRITE));
3601 }
3602 
3603 /*
3604  * Due to historical reasons, old limits are: For variable-length devices:
3605  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3606  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3607  * (let it through unmodified. For fixed-length record devices:
3608  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3609  *
3610  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3611  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3612  * command to the drive).
3613  *
3614  */
3615 static void
3616 st_minphys(struct buf *bp)
3617 {
3618 	struct scsi_tape *un;
3619 
3620 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3621 
3622 	ST_FUNC(ST_DEVINFO, st_minphys);
3623 
3624 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3625 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3626 	    bp->b_bcount);
3627 
3628 	if (un->un_allow_large_xfer) {
3629 
3630 		/*
3631 		 * check un_maxbsize for variable length devices only
3632 		 */
3633 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3634 			bp->b_bcount = un->un_maxbsize;
3635 		}
3636 		/*
3637 		 * can't go more that HBA maxdma limit in either fixed-length
3638 		 * or variable-length tape drives.
3639 		 */
3640 		if (bp->b_bcount > un->un_maxdma) {
3641 			bp->b_bcount = un->un_maxdma;
3642 		}
3643 	} else {
3644 
3645 		/*
3646 		 *  use old fixed limits
3647 		 */
3648 		if (un->un_bsize == 0) {
3649 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3650 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3651 			}
3652 		} else {
3653 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3654 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3655 			}
3656 		}
3657 	}
3658 
3659 	/*
3660 	 * For regular raw I/O and Fixed Block length devices, make sure
3661 	 * the adjusted block count is a whole multiple of the device
3662 	 * block size.
3663 	 */
3664 	if (bp != un->un_sbufp && un->un_bsize) {
3665 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3666 	}
3667 }
3668 
3669 static int
3670 st_rw(dev_t dev, struct uio *uio, int flag)
3671 {
3672 	int rval = 0;
3673 	long len;
3674 
3675 	GET_SOFT_STATE(dev);
3676 
3677 	ST_FUNC(ST_DEVINFO, st_rw);
3678 
3679 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3680 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3681 	    (flag == B_READ ? rd_str: wr_str));
3682 
3683 	/* get local copy of transfer length */
3684 	len = uio->uio_iov->iov_len;
3685 
3686 	mutex_enter(ST_MUTEX);
3687 
3688 	/*
3689 	 * Clear error entry stack
3690 	 */
3691 	st_empty_error_stack(un);
3692 
3693 	/*
3694 	 * If in fixed block size mode and requested read or write
3695 	 * is not an even multiple of that block size.
3696 	 */
3697 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3698 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3699 		    "%s: not modulo %d block size\n",
3700 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3701 		rval = EINVAL;
3702 	}
3703 
3704 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3705 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3706 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3707 		    "%s: not modulo %d device granularity\n",
3708 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3709 		rval = EINVAL;
3710 	}
3711 
3712 	if (rval != 0) {
3713 		un->un_errno = rval;
3714 		mutex_exit(ST_MUTEX);
3715 		return (rval);
3716 	}
3717 
3718 	/*
3719 	 * Reset this so it can be set if Berkeley and read over a filemark.
3720 	 */
3721 	un->un_silent_skip = 0;
3722 	mutex_exit(ST_MUTEX);
3723 
3724 	len = uio->uio_resid;
3725 
3726 	rval = physio(st_strategy, (struct buf *)NULL,
3727 	    dev, flag, st_minphys, uio);
3728 	/*
3729 	 * if we have hit logical EOT during this xfer and there is not a
3730 	 * full residue, then set eof back  to ST_EOM to make sure that
3731 	 * the user will see at least one zero write
3732 	 * after this short write
3733 	 */
3734 	mutex_enter(ST_MUTEX);
3735 	if (un->un_pos.eof > ST_NO_EOF) {
3736 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3737 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3738 	}
3739 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3740 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3741 			un->un_pos.eof = ST_EOM;
3742 		} else if (uio->uio_resid == len) {
3743 			un->un_pos.eof = ST_NO_EOF;
3744 		}
3745 	}
3746 
3747 	if (un->un_silent_skip && uio->uio_resid != len) {
3748 		un->un_pos.eof = ST_EOF;
3749 		un->un_pos.blkno = un->un_save_blkno;
3750 		un->un_pos.fileno--;
3751 	}
3752 
3753 	un->un_errno = rval;
3754 
3755 	mutex_exit(ST_MUTEX);
3756 
3757 	return (rval);
3758 }
3759 
3760 static int
3761 st_arw(dev_t dev, struct aio_req *aio, int flag)
3762 {
3763 	struct uio *uio = aio->aio_uio;
3764 	int rval = 0;
3765 	long len;
3766 
3767 	GET_SOFT_STATE(dev);
3768 
3769 	ST_FUNC(ST_DEVINFO, st_arw);
3770 
3771 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3772 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3773 	    (flag == B_READ ? rd_str: wr_str));
3774 
3775 	/* get local copy of transfer length */
3776 	len = uio->uio_iov->iov_len;
3777 
3778 	mutex_enter(ST_MUTEX);
3779 
3780 	/*
3781 	 * If in fixed block size mode and requested read or write
3782 	 * is not an even multiple of that block size.
3783 	 */
3784 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3785 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3786 		    "%s: not modulo %d block size\n",
3787 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3788 		rval = EINVAL;
3789 	}
3790 
3791 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3792 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3793 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3794 		    "%s: not modulo %d device granularity\n",
3795 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3796 		rval = EINVAL;
3797 	}
3798 
3799 	if (rval != 0) {
3800 		un->un_errno = rval;
3801 		mutex_exit(ST_MUTEX);
3802 		return (rval);
3803 	}
3804 
3805 	mutex_exit(ST_MUTEX);
3806 
3807 	len = uio->uio_resid;
3808 
3809 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3810 
3811 	/*
3812 	 * if we have hit logical EOT during this xfer and there is not a
3813 	 * full residue, then set eof back  to ST_EOM to make sure that
3814 	 * the user will see at least one zero write
3815 	 * after this short write
3816 	 *
3817 	 * we keep this here just in case the application is not using
3818 	 * persistent errors
3819 	 */
3820 	mutex_enter(ST_MUTEX);
3821 	if (un->un_pos.eof > ST_NO_EOF) {
3822 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3823 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3824 	}
3825 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3826 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3827 			un->un_pos.eof = ST_EOM;
3828 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3829 			un->un_pos.eof = ST_NO_EOF;
3830 		}
3831 	}
3832 	un->un_errno = rval;
3833 	mutex_exit(ST_MUTEX);
3834 
3835 	return (rval);
3836 }
3837 
3838 
3839 
3840 static int
3841 st_strategy(struct buf *bp)
3842 {
3843 	struct scsi_tape *un;
3844 	dev_t dev = bp->b_edev;
3845 
3846 	/*
3847 	 * validate arguments
3848 	 */
3849 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3850 		bp->b_resid = bp->b_bcount;
3851 		mutex_enter(ST_MUTEX);
3852 		st_bioerror(bp, ENXIO);
3853 		mutex_exit(ST_MUTEX);
3854 		goto error;
3855 	}
3856 
3857 	ST_ENTR(ST_DEVINFO, st_strategy);
3858 
3859 	mutex_enter(ST_MUTEX);
3860 
3861 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3862 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3863 	}
3864 
3865 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3866 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3867 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3868 
3869 	/*
3870 	 * If persistent errors have been flagged, just nix this one. We wait
3871 	 * for any outstanding I/O's below, so we will be in order.
3872 	 */
3873 	if (IS_PE_FLAG_SET(un)) {
3874 		goto exit;
3875 	}
3876 
3877 	if (bp != un->un_sbufp) {
3878 		char reading = bp->b_flags & B_READ;
3879 		int wasopening = 0;
3880 
3881 		/*
3882 		 * If we haven't done/checked reservation on the tape unit
3883 		 * do it now.
3884 		 */
3885 		if ((un->un_rsvd_status &
3886 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
3887 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
3888 				if (st_reserve_release(un, ST_RESERVE)) {
3889 					st_bioerror(bp, un->un_errno);
3890 					goto exit;
3891 				}
3892 			} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3893 				/*
3894 				 * Enter here to restore position for possible
3895 				 * resets when the device was closed and opened
3896 				 * in O_NDELAY mode subsequently
3897 				 */
3898 				un->un_state = ST_STATE_INITIALIZING;
3899 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3900 				    0, SYNC_CMD);
3901 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3902 			}
3903 			un->un_rsvd_status |= ST_INIT_RESERVE;
3904 		}
3905 
3906 		/*
3907 		 * If we are offline, we have to initialize everything first.
3908 		 * This is to handle either when opened with O_NDELAY, or
3909 		 * we just got a new tape in the drive, after an offline.
3910 		 * We don't observe O_NDELAY past the open,
3911 		 * as it will not make sense for tapes.
3912 		 */
3913 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3914 			/* reset state to avoid recursion */
3915 			un->un_state = ST_STATE_INITIALIZING;
3916 			if (st_tape_init(dev)) {
3917 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3918 				    "stioctl : OFFLINE init failure ");
3919 				un->un_state = ST_STATE_OFFLINE;
3920 				un->un_pos.pmode = invalid;
3921 				goto b_done_err;
3922 			}
3923 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3924 		}
3925 		/*
3926 		 * Check for legal operations
3927 		 */
3928 		if (un->un_pos.pmode == invalid) {
3929 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3930 			    "strategy with un->un_pos.pmode invalid\n");
3931 			goto b_done_err;
3932 		}
3933 
3934 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3935 		    "st_strategy(): regular io\n");
3936 
3937 		/*
3938 		 * Process this first. If we were reading, and we're pending
3939 		 * logical eot, that means we've bumped one file mark too far.
3940 		 */
3941 
3942 		/*
3943 		 * Recursion warning: st_cmd will route back through here.
3944 		 */
3945 		if (un->un_pos.eof == ST_EOT_PENDING) {
3946 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3947 				un->un_pos.pmode = invalid;
3948 				un->un_density_known = 0;
3949 				goto b_done_err;
3950 			}
3951 			un->un_pos.blkno = 0; /* fix up block number.. */
3952 			un->un_pos.eof = ST_EOT;
3953 		}
3954 
3955 		/*
3956 		 * If we are in the process of opening, we may have to
3957 		 * determine/set the correct density. We also may have
3958 		 * to do a test_append (if QIC) to see whether we are
3959 		 * in a position to append to the end of the tape.
3960 		 *
3961 		 * If we're already at logical eot, we transition
3962 		 * to ST_NO_EOF. If we're at physical eot, we punt
3963 		 * to the switch statement below to handle.
3964 		 */
3965 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3966 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3967 
3968 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3969 				if (st_determine_density(dev, (int)reading)) {
3970 					goto b_done_err;
3971 				}
3972 			}
3973 
3974 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3975 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3976 			    un->un_pos.fileno, (int)reading,
3977 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3978 			    un->un_pos.eof);
3979 
3980 			if (!reading && un->un_pos.eof != ST_EOM) {
3981 				if (un->un_pos.eof == ST_EOT) {
3982 					un->un_pos.eof = ST_NO_EOF;
3983 				} else if (un->un_pos.pmode != invalid &&
3984 				    (un->un_dp->options & ST_QIC)) {
3985 					/*
3986 					 * st_test_append() will do it all
3987 					 */
3988 					st_test_append(bp);
3989 					goto done;
3990 				}
3991 			}
3992 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3993 				wasopening = 1;
3994 			}
3995 			un->un_laststate = un->un_state;
3996 			un->un_state = ST_STATE_OPEN;
3997 		}
3998 
3999 
4000 		/*
4001 		 * Process rest of END OF FILE and END OF TAPE conditions
4002 		 */
4003 
4004 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4005 		    "eof=%x, wasopening=%x\n",
4006 		    un->un_pos.eof, wasopening);
4007 
4008 		switch (un->un_pos.eof) {
4009 		case ST_EOM:
4010 			/*
4011 			 * This allows writes to proceed past physical
4012 			 * eot. We'll *really* be in trouble if the
4013 			 * user continues blindly writing data too
4014 			 * much past this point (unwind the tape).
4015 			 * Physical eot really means 'early warning
4016 			 * eot' in this context.
4017 			 *
4018 			 * Every other write from now on will succeed
4019 			 * (if sufficient  tape left).
4020 			 * This write will return with resid == count
4021 			 * but the next one should be successful
4022 			 *
4023 			 * Note that we only transition to logical EOT
4024 			 * if the last state wasn't the OPENING state.
4025 			 * We explicitly prohibit running up to physical
4026 			 * eot, closing the device, and then re-opening
4027 			 * to proceed. Trailer records may only be gotten
4028 			 * at by keeping the tape open after hitting eot.
4029 			 *
4030 			 * Also note that ST_EOM cannot be set by reading-
4031 			 * this can only be set during writing. Reading
4032 			 * up to the end of the tape gets a blank check
4033 			 * or a double-filemark indication (ST_EOT_PENDING),
4034 			 * and we prohibit reading after that point.
4035 			 *
4036 			 */
4037 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4038 			if (wasopening == 0) {
4039 				/*
4040 				 * this allows st_rw() to reset it back to
4041 				 * ST_EOM to make sure that the application
4042 				 * will see a zero write
4043 				 */
4044 				un->un_pos.eof = ST_WRITE_AFTER_EOM;
4045 			}
4046 			un->un_status = SUN_KEY_EOT;
4047 			goto b_done;
4048 
4049 		case ST_WRITE_AFTER_EOM:
4050 		case ST_EOT:
4051 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4052 			un->un_status = SUN_KEY_EOT;
4053 			if (SVR4_BEHAVIOR && reading) {
4054 				goto b_done_err;
4055 			}
4056 
4057 			if (reading) {
4058 				goto b_done;
4059 			}
4060 			un->un_pos.eof = ST_NO_EOF;
4061 			break;
4062 
4063 		case ST_EOF_PENDING:
4064 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4065 			    "EOF PENDING\n");
4066 			un->un_status = SUN_KEY_EOF;
4067 			if (SVR4_BEHAVIOR) {
4068 				un->un_pos.eof = ST_EOF;
4069 				goto b_done;
4070 			}
4071 			/* FALLTHROUGH */
4072 		case ST_EOF:
4073 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4074 			un->un_status = SUN_KEY_EOF;
4075 			if (SVR4_BEHAVIOR) {
4076 				goto b_done_err;
4077 			}
4078 
4079 			if (BSD_BEHAVIOR) {
4080 				un->un_pos.eof = ST_NO_EOF;
4081 				un->un_pos.fileno += 1;
4082 				un->un_pos.blkno   = 0;
4083 			}
4084 
4085 			if (reading) {
4086 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4087 				    "now file %d (read)\n",
4088 				    un->un_pos.fileno);
4089 				goto b_done;
4090 			}
4091 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4092 			    "now file %d (write)\n", un->un_pos.fileno);
4093 			break;
4094 		default:
4095 			un->un_status = 0;
4096 			break;
4097 		}
4098 	}
4099 
4100 	bp->b_flags &= ~(B_DONE);
4101 	st_bioerror(bp, 0);
4102 	bp->av_forw = NULL;
4103 	bp->b_resid = 0;
4104 	SET_BP_PKT(bp, 0);
4105 
4106 
4107 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4108 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4109 	    " pkt=0x%p\n",
4110 	    (void *)bp->b_forw, bp->b_bcount,
4111 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4112 
4113 #ifdef	__x86
4114 	/*
4115 	 * We will replace bp with a new bp that can do big blk xfer
4116 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4117 	 *
4118 	 * Also, we need to make sure that we're handling real I/O
4119 	 * by checking group 0/1 SCSI I/O commands, if needed
4120 	 */
4121 	if (bp->b_bcount > un->un_maxdma_arch &&
4122 	    (bp != un->un_sbufp					||
4123 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ		||
4124 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G1	||
4125 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE	||
4126 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G1)) {
4127 		mutex_exit(ST_MUTEX);
4128 		bp = st_get_bigblk_bp(bp);
4129 		mutex_enter(ST_MUTEX);
4130 	}
4131 #endif
4132 
4133 	/* put on wait queue */
4134 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4135 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4136 	    (void *)un->un_quef, (void *)bp);
4137 
4138 	if (un->un_quef) {
4139 		un->un_quel->b_actf = bp;
4140 	} else {
4141 		un->un_quef = bp;
4142 	}
4143 	un->un_quel = bp;
4144 
4145 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4146 
4147 	st_start(un);
4148 
4149 done:
4150 	mutex_exit(ST_MUTEX);
4151 	return (0);
4152 
4153 
4154 error:
4155 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4156 	    "st_strategy: error exit\n");
4157 
4158 	biodone(bp);
4159 	return (0);
4160 
4161 b_done_err:
4162 	st_bioerror(bp, EIO);
4163 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4164 	    "st_strategy : EIO b_done_err\n");
4165 
4166 b_done:
4167 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4168 	    "st_strategy: b_done\n");
4169 
4170 exit:
4171 	/*
4172 	 * make sure no commands are outstanding or waiting before closing,
4173 	 * so we can guarantee order
4174 	 */
4175 	st_wait_for_io(un);
4176 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4177 
4178 	/* override errno here, if persistent errors were flagged */
4179 	if (IS_PE_FLAG_SET(un))
4180 		bioerror(bp, un->un_errno);
4181 
4182 	mutex_exit(ST_MUTEX);
4183 
4184 	biodone(bp);
4185 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4186 	return (0);
4187 }
4188 
4189 
4190 
4191 /*
4192  * this routine spaces forward over filemarks
4193  */
4194 static int
4195 st_space_fmks(dev_t dev, int count)
4196 {
4197 	int rval = 0;
4198 
4199 	GET_SOFT_STATE(dev);
4200 
4201 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4202 
4203 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4204 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
4205 
4206 	ASSERT(mutex_owned(ST_MUTEX));
4207 
4208 	/*
4209 	 * the risk with doing only one space operation is that we
4210 	 * may accidentily jump in old data
4211 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4212 	 * because the 8200 does not append a marker; in order not to
4213 	 * sacrifice the fast file skip, we do a slow skip if the low
4214 	 * density device has been opened
4215 	 */
4216 
4217 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4218 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
4219 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4220 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4221 			    "space_fmks : EIO can't do space cmd #1\n");
4222 			rval = EIO;
4223 		}
4224 	} else {
4225 		while (count > 0) {
4226 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4227 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4228 				    "space_fmks : EIO can't do space cmd #2\n");
4229 				rval = EIO;
4230 				break;
4231 			}
4232 			count -= 1;
4233 			/*
4234 			 * read a block to see if we have reached
4235 			 * end of medium (double filemark for reel or
4236 			 * medium error for others)
4237 			 */
4238 			if (count > 0) {
4239 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
4240 				    SYNC_CMD)) {
4241 					ST_DEBUG2(ST_DEVINFO, st_label,
4242 					    SCSI_DEBUG,
4243 					    "space_fmks : EIO can't do "
4244 					    "space cmd #3\n");
4245 					rval = EIO;
4246 					break;
4247 				}
4248 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4249 				    (un->un_dp->options & ST_REEL)) {
4250 					un->un_status = SUN_KEY_EOT;
4251 					ST_DEBUG2(ST_DEVINFO, st_label,
4252 					    SCSI_DEBUG,
4253 					    "space_fmks : EIO ST_REEL\n");
4254 					rval = EIO;
4255 					break;
4256 				} else if (IN_EOF(un->un_pos)) {
4257 					un->un_pos.eof = ST_NO_EOF;
4258 					un->un_pos.fileno++;
4259 					un->un_pos.blkno = 0;
4260 					count--;
4261 				} else if (un->un_pos.eof > ST_EOF) {
4262 					ST_DEBUG2(ST_DEVINFO, st_label,
4263 					    SCSI_DEBUG,
4264 					    "space_fmks, EIO > ST_EOF\n");
4265 					rval = EIO;
4266 					break;
4267 				}
4268 
4269 			}
4270 		}
4271 		un->un_err_resid = count;
4272 		COPY_POS(&un->un_pos, &un->un_err_pos);
4273 	}
4274 	ASSERT(mutex_owned(ST_MUTEX));
4275 	return (rval);
4276 }
4277 
4278 /*
4279  * this routine spaces to EOD
4280  *
4281  * it keeps track of the current filenumber and returns the filenumber after
4282  * the last successful space operation, we keep the number high because as
4283  * tapes are getting larger, the possibility of more and more files exist,
4284  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4285  * soon
4286  */
4287 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4288 
4289 static int
4290 st_find_eod(dev_t dev)
4291 {
4292 	tapepos_t savepos;
4293 	int sp_type;
4294 	struct scsi_tape *un;
4295 	int instance;
4296 	int result;
4297 
4298 	instance = MTUNIT(dev);
4299 	un = ddi_get_soft_state(st_state, instance);
4300 	if (un == NULL) {
4301 		return (-1);
4302 	}
4303 
4304 	ST_FUNC(ST_DEVINFO, st_find_eod);
4305 
4306 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4307 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", dev, un->un_pos.fileno);
4308 
4309 	ASSERT(mutex_owned(ST_MUTEX));
4310 
4311 	COPY_POS(&savepos, &un->un_pos);
4312 
4313 	/*
4314 	 * see if the drive is smart enough to do the skips in
4315 	 * one operation; 1/2" use two filemarks
4316 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4317 	 * because the 8200 does not append a marker; in order not to
4318 	 * sacrifice the fast file skip, we do a slow skip if the low
4319 	 * density device has been opened
4320 	 */
4321 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4322 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4323 		    (MT_DENSITY(dev) == 0)) {
4324 			sp_type = Fmk(1);
4325 		} else if (un->un_pos.pmode == logical) {
4326 			sp_type = SPACE(SP_EOD, 0);
4327 		} else {
4328 			sp_type = Fmk(MAX_SKIP);
4329 		}
4330 	} else {
4331 		sp_type = Fmk(1);
4332 	}
4333 
4334 	for (;;) {
4335 		result = st_cmd(dev, SCMD_SPACE, sp_type, SYNC_CMD);
4336 
4337 		if (result == 0) {
4338 			COPY_POS(&savepos, &un->un_pos);
4339 		}
4340 
4341 		if (sp_type == SPACE(SP_EOD, 0)) {
4342 			if (result != 0) {
4343 				sp_type = Fmk(MAX_SKIP);
4344 				continue;
4345 			}
4346 
4347 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4348 			    "st_find_eod: 0x%"PRIx64"\n",
4349 			    savepos.lgclblkno);
4350 			/*
4351 			 * What we return will become the current file position.
4352 			 * After completing the space command with the position
4353 			 * mode that is not invalid a read position command will
4354 			 * be automaticly issued. If the drive support the long
4355 			 * read position format a valid file position can be
4356 			 * returned.
4357 			 */
4358 			return (un->un_pos.fileno);
4359 		}
4360 
4361 		if (result != 0) {
4362 			break;
4363 		}
4364 
4365 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4366 		    "count=%x, eof=%x, status=%x\n",
4367 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4368 
4369 		/*
4370 		 * If we're not EOM smart,  space a record
4371 		 * to see whether we're now in the slot between
4372 		 * the two sequential filemarks that logical
4373 		 * EOM consists of (REEL) or hit nowhere land
4374 		 * (8mm).
4375 		 */
4376 		if (sp_type == Fmk(1)) {
4377 			/*
4378 			 * no fast skipping, check a record
4379 			 */
4380 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4381 				break;
4382 			}
4383 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4384 			    (un->un_dp->options & ST_REEL)) {
4385 				un->un_status = KEY_BLANK_CHECK;
4386 				un->un_pos.fileno++;
4387 				un->un_pos.blkno = 0;
4388 				break;
4389 			}
4390 			if (IN_EOF(un->un_pos)) {
4391 				un->un_pos.eof = ST_NO_EOF;
4392 				un->un_pos.fileno++;
4393 				un->un_pos.blkno = 0;
4394 			}
4395 			if (un->un_pos.eof > ST_EOF) {
4396 				break;
4397 			}
4398 		} else {
4399 			if (un->un_pos.eof > ST_EOF) {
4400 				break;
4401 			}
4402 		}
4403 	}
4404 
4405 	if (un->un_dp->options & ST_KNOWS_EOD) {
4406 		COPY_POS(&savepos, &un->un_pos);
4407 	}
4408 
4409 	ASSERT(mutex_owned(ST_MUTEX));
4410 
4411 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4412 	    "st_find_eod: %x\n", savepos.fileno);
4413 	return (savepos.fileno);
4414 }
4415 
4416 
4417 /*
4418  * this routine is frequently used in ioctls below;
4419  * it determines whether we know the density and if not will
4420  * determine it
4421  * if we have written the tape before, one or more filemarks are written
4422  *
4423  * depending on the stepflag, the head is repositioned to where it was before
4424  * the filemarks were written in order not to confuse step counts
4425  */
4426 #define	STEPBACK    0
4427 #define	NO_STEPBACK 1
4428 
4429 static int
4430 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4431 {
4432 
4433 	GET_SOFT_STATE(dev);
4434 
4435 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4436 
4437 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4438 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4439 	    "\n", dev, wfm, mode, stepflag);
4440 
4441 	ASSERT(mutex_owned(ST_MUTEX));
4442 
4443 	/*
4444 	 * If we don't yet know the density of the tape we have inserted,
4445 	 * we have to either unconditionally set it (if we're 'writing'),
4446 	 * or we have to determine it. As side effects, check for any
4447 	 * write-protect errors, and for the need to put out any file-marks
4448 	 * before positioning a tape.
4449 	 *
4450 	 * If we are going to be spacing forward, and we haven't determined
4451 	 * the tape density yet, we have to do so now...
4452 	 */
4453 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4454 		if (st_determine_density(dev, mode)) {
4455 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4456 			    "check_density_or_wfm : EIO can't determine "
4457 			    "density\n");
4458 			un->un_errno = EIO;
4459 			return (EIO);
4460 		}
4461 		/*
4462 		 * Presumably we are at BOT. If we attempt to write, it will
4463 		 * either work okay, or bomb. We don't do a st_test_append
4464 		 * unless we're past BOT.
4465 		 */
4466 		un->un_laststate = un->un_state;
4467 		un->un_state = ST_STATE_OPEN;
4468 
4469 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4470 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4471 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4472 
4473 		tapepos_t spos;
4474 
4475 		COPY_POS(&spos, &un->un_pos);
4476 
4477 		/*
4478 		 * We need to write one or two filemarks.
4479 		 * In the case of the HP, we need to
4480 		 * position the head between the two
4481 		 * marks.
4482 		 */
4483 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4484 			wfm = un->un_fmneeded;
4485 			un->un_fmneeded = 0;
4486 		}
4487 
4488 		if (st_write_fm(dev, wfm)) {
4489 			un->un_pos.pmode = invalid;
4490 			un->un_density_known = 0;
4491 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4492 			    "check_density_or_wfm : EIO can't write fm\n");
4493 			un->un_errno = EIO;
4494 			return (EIO);
4495 		}
4496 
4497 		if (stepflag == STEPBACK) {
4498 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
4499 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4500 				    "check_density_or_wfm : EIO can't space "
4501 				    "(-wfm)\n");
4502 				un->un_errno = EIO;
4503 				return (EIO);
4504 			}
4505 			COPY_POS(&un->un_pos, &spos);
4506 		}
4507 	}
4508 
4509 	/*
4510 	 * Whatever we do at this point clears the state of the eof flag.
4511 	 */
4512 
4513 	un->un_pos.eof = ST_NO_EOF;
4514 
4515 	/*
4516 	 * If writing, let's check that we're positioned correctly
4517 	 * at the end of tape before issuing the next write.
4518 	 */
4519 	if (un->un_read_only == RDWR) {
4520 		un->un_test_append = 1;
4521 	}
4522 
4523 	ASSERT(mutex_owned(ST_MUTEX));
4524 	return (0);
4525 }
4526 
4527 
4528 /*
4529  * Wait for all outstaning I/O's to complete
4530  *
4531  * we wait on both ncmds and the wait queue for times when we are flushing
4532  * after persistent errors are flagged, which is when ncmds can be 0, and the
4533  * queue can still have I/O's.  This way we preserve order of biodone's.
4534  */
4535 static void
4536 st_wait_for_io(struct scsi_tape *un)
4537 {
4538 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4539 	ASSERT(mutex_owned(ST_MUTEX));
4540 	while (un->un_ncmds && un->un_quef) { /* XXX fix for async write@EOM */
4541 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4542 	}
4543 }
4544 
4545 /*
4546  * This routine implements the ioctl calls.  It is called
4547  * from the device switch at normal priority.
4548  */
4549 /*ARGSUSED*/
4550 static int
4551 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4552     int *rval_p)
4553 {
4554 	int tmp, rval = 0;
4555 
4556 	GET_SOFT_STATE(dev);
4557 
4558 	ST_ENTR(ST_DEVINFO, st_ioctl);
4559 
4560 	mutex_enter(ST_MUTEX);
4561 
4562 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4563 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4564 	    "pe_flag = %d\n",
4565 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4566 	    IS_PE_FLAG_SET(un));
4567 
4568 	/*
4569 	 * We don't want to block on these, so let them through
4570 	 * and we don't care about setting driver states here.
4571 	 */
4572 	if ((cmd == MTIOCGETDRIVETYPE) ||
4573 	    (cmd == MTIOCGUARANTEEDORDER) ||
4574 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4575 		goto check_commands;
4576 	}
4577 
4578 	/*
4579 	 * We clear error entry stack except command
4580 	 * MTIOCGETERROR and MTIOCGET
4581 	 */
4582 	if ((cmd != MTIOCGETERROR) &&
4583 	    (cmd != MTIOCGET)) {
4584 		st_empty_error_stack(un);
4585 	}
4586 
4587 	/*
4588 	 * wait for all outstanding commands to complete, or be dequeued.
4589 	 * And because ioctl's are synchronous commands, any return value
4590 	 * after this,  will be in order
4591 	 */
4592 	st_wait_for_io(un);
4593 
4594 	/*
4595 	 * allow only a through clear errors and persistent status, and
4596 	 * status
4597 	 */
4598 	if (IS_PE_FLAG_SET(un)) {
4599 		if ((cmd == MTIOCLRERR) ||
4600 		    (cmd == MTIOCPERSISTENT) ||
4601 		    (cmd == MTIOCGET)) {
4602 			goto check_commands;
4603 		} else {
4604 			rval = un->un_errno;
4605 			goto exit;
4606 		}
4607 	}
4608 
4609 	un->un_throttle = 1;	/* > 1 will never happen here */
4610 	un->un_errno = 0;	/* start clean from here */
4611 
4612 	/*
4613 	 * first and foremost, handle any ST_EOT_PENDING cases.
4614 	 * That is, if a logical eot is pending notice, notice it.
4615 	 */
4616 	if (un->un_pos.eof == ST_EOT_PENDING) {
4617 		int resid = un->un_err_resid;
4618 		uchar_t status = un->un_status;
4619 		uchar_t lastop = un->un_lastop;
4620 
4621 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
4622 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4623 			    "stioctl : EIO can't space fmk(-1)\n");
4624 			rval = EIO;
4625 			goto exit;
4626 		}
4627 		un->un_lastop = lastop; /* restore last operation */
4628 		if (status == SUN_KEY_EOF) {
4629 			un->un_status = SUN_KEY_EOT;
4630 		} else {
4631 			un->un_status = status;
4632 		}
4633 		un->un_err_resid  = resid;
4634 		/* fix up block number */
4635 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4636 		/* now we're at logical eot */
4637 		un->un_pos.eof = ST_EOT;
4638 	}
4639 
4640 	/*
4641 	 * now, handle the rest of the situations
4642 	 */
4643 check_commands:
4644 	switch (cmd) {
4645 	case MTIOCGET:
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 mtget32		mtg_local32;
4653 		struct mtget32 		*mtget_32 = &mtg_local32;
4654 #endif /* _MULTI_DATAMODEL */
4655 
4656 			/* Get tape status */
4657 		struct mtget mtg_local;
4658 		struct mtget *mtget = &mtg_local;
4659 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4660 		    "st_ioctl: MTIOCGET\n");
4661 
4662 		bzero((caddr_t)mtget, sizeof (struct mtget));
4663 		mtget->mt_erreg = un->un_status;
4664 		mtget->mt_resid = un->un_err_resid;
4665 		mtget->mt_dsreg = un->un_retry_ct;
4666 		if (un->un_err_pos.pmode == legacy) {
4667 			mtget->mt_fileno = un->un_err_pos.fileno;
4668 		} else {
4669 			mtget->mt_fileno = -1;
4670 		}
4671 		mtget->mt_blkno = un->un_err_pos.blkno;
4672 		mtget->mt_type = un->un_dp->type;
4673 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4674 		if (un->un_read_pos_type != NO_POS) {
4675 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4676 		}
4677 		if (un->un_dp->options & ST_REEL) {
4678 			mtget->mt_flags |= MTF_REEL;
4679 			mtget->mt_bf = 20;
4680 		} else {		/* 1/4" cartridges */
4681 			switch (mtget->mt_type) {
4682 			/* Emulex cartridge tape */
4683 			case MT_ISMT02:
4684 				mtget->mt_bf = 40;
4685 				break;
4686 			default:
4687 				mtget->mt_bf = 126;
4688 				break;
4689 			}
4690 		}
4691 
4692 		/*
4693 		 * If large transfers are allowed and drive options
4694 		 * has no record size limit set. Calculate blocking
4695 		 * factor from the lesser of maxbsize and maxdma.
4696 		 */
4697 		if ((un->un_allow_large_xfer) &&
4698 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4699 			mtget->mt_bf = min(un->un_maxbsize,
4700 			    un->un_maxdma) / SECSIZE;
4701 		}
4702 
4703 			if (un->un_read_only == WORM ||
4704 			    un->un_read_only == RDWORM) {
4705 				mtget->mt_flags |= MTF_WORM_MEDIA;
4706 			}
4707 
4708 			rval = st_check_clean_bit(dev);
4709 			if (rval == -1) {
4710 				rval = EIO;
4711 				goto exit;
4712 			} else {
4713 				mtget->mt_flags |= (ushort_t)rval;
4714 				rval = 0;
4715 			}
4716 
4717 		un->un_status = 0;		/* Reset status */
4718 		un->un_err_resid = 0;
4719 		tmp = sizeof (struct mtget);
4720 
4721 #ifdef _MULTI_DATAMODEL
4722 
4723 		switch (ddi_model_convert_from(flag & FMODELS)) {
4724 		case DDI_MODEL_ILP32:
4725 			/*
4726 			 * Convert 64 bit back to 32 bit before doing
4727 			 * copyout. This is what the ILP32 app expects.
4728 			 */
4729 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4730 			mtget_32->mt_resid = 	mtget->mt_resid;
4731 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4732 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4733 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4734 			mtget_32->mt_type =  	mtget->mt_type;
4735 			mtget_32->mt_flags = 	mtget->mt_flags;
4736 			mtget_32->mt_bf = 	mtget->mt_bf;
4737 
4738 			if (ddi_copyout(mtget_32, (void *)arg,
4739 			    sizeof (struct mtget32), flag)) {
4740 				rval = EFAULT;
4741 			}
4742 			break;
4743 
4744 		case DDI_MODEL_NONE:
4745 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4746 				rval = EFAULT;
4747 			}
4748 			break;
4749 		}
4750 #else /* ! _MULTI_DATAMODE */
4751 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4752 			rval = EFAULT;
4753 		}
4754 #endif /* _MULTI_DATAMODE */
4755 
4756 		break;
4757 	}
4758 	case MTIOCGETERROR:
4759 			/*
4760 			 * get error entry from error stack
4761 			 */
4762 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4763 			    "st_ioctl: MTIOCGETERROR\n");
4764 
4765 			rval = st_get_error_entry(un, arg, flag);
4766 
4767 			break;
4768 
4769 	case MTIOCSTATE:
4770 		{
4771 			/*
4772 			 * return when media presence matches state
4773 			 */
4774 			enum mtio_state state;
4775 
4776 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4777 			    "st_ioctl: MTIOCSTATE\n");
4778 
4779 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4780 				rval = EFAULT;
4781 
4782 			mutex_exit(ST_MUTEX);
4783 
4784 			rval = st_check_media(dev, state);
4785 
4786 			mutex_enter(ST_MUTEX);
4787 
4788 			if (rval != 0) {
4789 				break;
4790 			}
4791 
4792 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4793 			    sizeof (int), flag))
4794 				rval = EFAULT;
4795 			break;
4796 
4797 		}
4798 
4799 	case MTIOCGETDRIVETYPE:
4800 		{
4801 #ifdef _MULTI_DATAMODEL
4802 		/*
4803 		 * For use when a 32 bit app makes a call into a
4804 		 * 64 bit ioctl
4805 		 */
4806 		struct mtdrivetype_request32	mtdtrq32;
4807 #endif /* _MULTI_DATAMODEL */
4808 
4809 			/*
4810 			 * return mtdrivetype
4811 			 */
4812 			struct mtdrivetype_request mtdtrq;
4813 			struct mtdrivetype mtdrtyp;
4814 			struct mtdrivetype *mtdt = &mtdrtyp;
4815 			struct st_drivetype *stdt = un->un_dp;
4816 
4817 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4818 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
4819 
4820 #ifdef _MULTI_DATAMODEL
4821 		switch (ddi_model_convert_from(flag & FMODELS)) {
4822 		case DDI_MODEL_ILP32:
4823 		{
4824 			if (ddi_copyin((void *)arg, &mtdtrq32,
4825 			    sizeof (struct mtdrivetype_request32), flag)) {
4826 				rval = EFAULT;
4827 				break;
4828 			}
4829 			mtdtrq.size = mtdtrq32.size;
4830 			mtdtrq.mtdtp =
4831 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
4832 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4833 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
4834 			break;
4835 		}
4836 		case DDI_MODEL_NONE:
4837 			if (ddi_copyin((void *)arg, &mtdtrq,
4838 			    sizeof (struct mtdrivetype_request), flag)) {
4839 				rval = EFAULT;
4840 				break;
4841 			}
4842 			break;
4843 		}
4844 
4845 #else /* ! _MULTI_DATAMODEL */
4846 		if (ddi_copyin((void *)arg, &mtdtrq,
4847 		    sizeof (struct mtdrivetype_request), flag)) {
4848 			rval = EFAULT;
4849 			break;
4850 		}
4851 #endif /* _MULTI_DATAMODEL */
4852 
4853 			/*
4854 			 * if requested size is < 0 then return
4855 			 * error.
4856 			 */
4857 			if (mtdtrq.size < 0) {
4858 				rval = EINVAL;
4859 				break;
4860 			}
4861 			bzero(mtdt, sizeof (struct mtdrivetype));
4862 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
4863 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
4864 			mtdt->type = stdt->type;
4865 			mtdt->bsize = stdt->bsize;
4866 			mtdt->options = stdt->options;
4867 			mtdt->max_rretries = stdt->max_rretries;
4868 			mtdt->max_wretries = stdt->max_wretries;
4869 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4870 				mtdt->densities[tmp] = stdt->densities[tmp];
4871 			}
4872 			mtdt->default_density = stdt->default_density;
4873 			/*
4874 			 * Speed hasn't been used since the hayday of reel tape.
4875 			 * For all drives not setting the option ST_KNOWS_MEDIA
4876 			 * the speed member renamed to mediatype are zeros.
4877 			 * Those drives that have ST_KNOWS_MEDIA set use the
4878 			 * new mediatype member which is used to figure the
4879 			 * type of media loaded.
4880 			 *
4881 			 * So as to not break applications speed in the
4882 			 * mtdrivetype structure is not renamed.
4883 			 */
4884 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4885 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4886 			}
4887 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4888 			mtdt->io_timeout = stdt->io_timeout;
4889 			mtdt->rewind_timeout = stdt->rewind_timeout;
4890 			mtdt->space_timeout = stdt->space_timeout;
4891 			mtdt->load_timeout = stdt->load_timeout;
4892 			mtdt->unload_timeout = stdt->unload_timeout;
4893 			mtdt->erase_timeout = stdt->erase_timeout;
4894 
4895 			/*
4896 			 * Limit the maximum length of the result to
4897 			 * sizeof (struct mtdrivetype).
4898 			 */
4899 			tmp = sizeof (struct mtdrivetype);
4900 			if (mtdtrq.size < tmp)
4901 				tmp = mtdtrq.size;
4902 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4903 				rval = EFAULT;
4904 			}
4905 			break;
4906 		}
4907 	case MTIOCPERSISTENT:
4908 		{
4909 			int persistence = 0;
4910 
4911 			if (ddi_copyin((void *)arg, &persistence,
4912 			    sizeof (int), flag)) {
4913 				rval = EFAULT;
4914 				break;
4915 			}
4916 
4917 			/* non zero sets it, only 0 turns it off */
4918 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4919 
4920 			if (un->un_persistence) {
4921 				TURN_PE_ON(un);
4922 			} else {
4923 				TURN_PE_OFF(un);
4924 			}
4925 
4926 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4927 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4928 			    un->un_persistence);
4929 
4930 			break;
4931 		}
4932 	case MTIOCPERSISTENTSTATUS:
4933 		{
4934 			int persistence = (int)un->un_persistence;
4935 
4936 			if (ddi_copyout(&persistence, (void *)arg,
4937 			    sizeof (int), flag)) {
4938 				rval = EFAULT;
4939 			}
4940 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4941 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4942 			    un->un_persistence);
4943 
4944 			break;
4945 		}
4946 
4947 
4948 	case MTIOCLRERR:
4949 		{
4950 			/* clear persistent errors */
4951 
4952 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4953 			    "st_ioctl: MTIOCLRERR\n");
4954 
4955 			CLEAR_PE(un);
4956 
4957 			break;
4958 		}
4959 
4960 	case MTIOCGUARANTEEDORDER:
4961 		{
4962 			/*
4963 			 * this is just a holder to make a valid ioctl and
4964 			 * it won't be in any earlier release
4965 			 */
4966 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4967 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4968 
4969 			break;
4970 		}
4971 
4972 	case MTIOCRESERVE:
4973 		{
4974 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4975 			    "st_ioctl: MTIOCRESERVE\n");
4976 
4977 			/*
4978 			 * Check if Reserve/Release is supported.
4979 			 */
4980 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4981 				rval = ENOTTY;
4982 				break;
4983 			}
4984 
4985 			rval = st_reserve_release(un, ST_RESERVE);
4986 
4987 			if (rval == 0) {
4988 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4989 			}
4990 			break;
4991 		}
4992 
4993 	case MTIOCRELEASE:
4994 		{
4995 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4996 			    "st_ioctl: MTIOCRELEASE\n");
4997 
4998 			/*
4999 			 * Check if Reserve/Release is supported.
5000 			 */
5001 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5002 				rval = ENOTTY;
5003 				break;
5004 			}
5005 
5006 			/*
5007 			 * Used to just clear ST_PRESERVE_RESERVE which
5008 			 * made the reservation release at next close.
5009 			 * As the user may have opened and then done a
5010 			 * persistant reservation we now need to drop
5011 			 * the reservation without closing if the user
5012 			 * attempts to do this.
5013 			 */
5014 			rval = st_reserve_release(un, ST_RELEASE);
5015 
5016 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5017 
5018 			break;
5019 		}
5020 
5021 	case MTIOCFORCERESERVE:
5022 		{
5023 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5024 			    "st_ioctl: MTIOCFORCERESERVE\n");
5025 
5026 			/*
5027 			 * Check if Reserve/Release is supported.
5028 			 */
5029 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5030 				rval = ENOTTY;
5031 				break;
5032 			}
5033 			/*
5034 			 * allow only super user to run this.
5035 			 */
5036 			if (drv_priv(cred_p) != 0) {
5037 				rval = EPERM;
5038 				break;
5039 			}
5040 			/*
5041 			 * Throw away reserve,
5042 			 * not using test-unit-ready
5043 			 * since reserve can succeed without tape being
5044 			 * present in the drive.
5045 			 */
5046 			(void) st_reserve_release(un, ST_RESERVE);
5047 
5048 			rval = st_take_ownership(dev);
5049 
5050 			break;
5051 		}
5052 
5053 	case USCSICMD:
5054 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5055 		    "st_ioctl: USCSICMD\n");
5056 	{
5057 		cred_t	*cr;
5058 		cr = ddi_get_cred();
5059 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5060 			rval = EPERM;
5061 		} else {
5062 			rval = st_ioctl_cmd(dev, (struct uscsi_cmd *)arg,
5063 			    flag);
5064 		}
5065 	}
5066 		break;
5067 
5068 	case MTIOCTOP:
5069 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5070 		    "st_ioctl: MTIOCTOP\n");
5071 		rval = st_mtioctop(un, arg, flag);
5072 		break;
5073 
5074 	case MTIOCLTOP:
5075 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5076 		    "st_ioctl: MTIOLCTOP\n");
5077 		rval = st_mtiocltop(un, arg, flag);
5078 		break;
5079 
5080 	case MTIOCREADIGNOREILI:
5081 		{
5082 			int set_ili;
5083 
5084 			if (ddi_copyin((void *)arg, &set_ili,
5085 			    sizeof (set_ili), flag)) {
5086 				rval = EFAULT;
5087 				break;
5088 			}
5089 
5090 			if (un->un_bsize) {
5091 				rval = ENOTTY;
5092 				break;
5093 			}
5094 
5095 			switch (set_ili) {
5096 			case 0:
5097 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5098 				break;
5099 
5100 			case 1:
5101 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5102 				break;
5103 
5104 			default:
5105 				rval = EINVAL;
5106 				break;
5107 			}
5108 			break;
5109 		}
5110 
5111 	case MTIOCREADIGNOREEOFS:
5112 		{
5113 			int ignore_eof;
5114 
5115 			if (ddi_copyin((void *)arg, &ignore_eof,
5116 			    sizeof (ignore_eof), flag)) {
5117 				rval = EFAULT;
5118 				break;
5119 			}
5120 
5121 			if (!(un->un_dp->options & ST_REEL)) {
5122 				rval = ENOTTY;
5123 				break;
5124 			}
5125 
5126 			switch (ignore_eof) {
5127 			case 0:
5128 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5129 				break;
5130 
5131 			case 1:
5132 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5133 				break;
5134 
5135 			default:
5136 				rval = EINVAL;
5137 				break;
5138 			}
5139 			break;
5140 		}
5141 
5142 	case MTIOCSHORTFMK:
5143 	{
5144 		int short_fmk;
5145 
5146 		if (ddi_copyin((void *)arg, &short_fmk,
5147 		    sizeof (short_fmk), flag)) {
5148 			rval = EFAULT;
5149 			break;
5150 		}
5151 
5152 		switch (un->un_dp->type) {
5153 		case ST_TYPE_EXB8500:
5154 		case ST_TYPE_EXABYTE:
5155 			if (!short_fmk) {
5156 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5157 			} else if (short_fmk == 1) {
5158 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5159 			} else {
5160 				rval = EINVAL;
5161 			}
5162 			break;
5163 
5164 		default:
5165 			rval = ENOTTY;
5166 			break;
5167 		}
5168 		break;
5169 	}
5170 
5171 	case MTIOCGETPOS:
5172 		rval = st_update_block_pos(un);
5173 		if (rval == 0) {
5174 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5175 			    sizeof (tapepos_t), flag)) {
5176 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5177 				    "MTIOCGETPOS copy out failed\n");
5178 				rval = EFAULT;
5179 			}
5180 		}
5181 		break;
5182 
5183 	case MTIOCRESTPOS:
5184 	{
5185 		tapepos_t dest;
5186 
5187 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5188 		    flag) != 0) {
5189 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5190 			    "MTIOCRESTPOS copy in failed\n");
5191 			rval = EFAULT;
5192 			break;
5193 		}
5194 		rval = st_validate_tapemarks(un, &dest);
5195 		if (rval != 0) {
5196 			rval = EIO;
5197 		}
5198 		break;
5199 	}
5200 	default:
5201 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5202 		    "st_ioctl: unknown ioctl\n");
5203 		rval = ENOTTY;
5204 	}
5205 
5206 exit:
5207 	if (!IS_PE_FLAG_SET(un)) {
5208 		un->un_errno = rval;
5209 	}
5210 
5211 	mutex_exit(ST_MUTEX);
5212 
5213 	return (rval);
5214 }
5215 
5216 
5217 /*
5218  * do some MTIOCTOP tape operations
5219  */
5220 static int
5221 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5222 {
5223 #ifdef _MULTI_DATAMODEL
5224 	/*
5225 	 * For use when a 32 bit app makes a call into a
5226 	 * 64 bit ioctl
5227 	 */
5228 	struct mtop32	mtop_32_for_64;
5229 #endif /* _MULTI_DATAMODEL */
5230 	struct mtop passed;
5231 	struct mtlop local;
5232 	int rval = 0;
5233 
5234 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5235 
5236 	ASSERT(mutex_owned(ST_MUTEX));
5237 
5238 #ifdef _MULTI_DATAMODEL
5239 	switch (ddi_model_convert_from(flag & FMODELS)) {
5240 	case DDI_MODEL_ILP32:
5241 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5242 		    sizeof (struct mtop32), flag)) {
5243 			return (EFAULT);
5244 		}
5245 		local.mt_op = mtop_32_for_64.mt_op;
5246 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5247 		break;
5248 
5249 	case DDI_MODEL_NONE:
5250 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5251 			return (EFAULT);
5252 		}
5253 		local.mt_op = passed.mt_op;
5254 		/* prevent sign extention */
5255 		local.mt_count = (UINT32_MAX & passed.mt_count);
5256 		break;
5257 	}
5258 
5259 #else /* ! _MULTI_DATAMODEL */
5260 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5261 		return (EFAULT);
5262 	}
5263 	local.mt_op = passed.mt_op;
5264 	/* prevent sign extention */
5265 	local.mt_count = (UINT32_MAX & passed.mt_count);
5266 #endif /* _MULTI_DATAMODEL */
5267 
5268 	rval = st_do_mtioctop(un, &local);
5269 
5270 #ifdef _MULTI_DATAMODEL
5271 	switch (ddi_model_convert_from(flag & FMODELS)) {
5272 	case DDI_MODEL_ILP32:
5273 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5274 			rval = ERANGE;
5275 			break;
5276 		}
5277 		/*
5278 		 * Convert 64 bit back to 32 bit before doing
5279 		 * copyout. This is what the ILP32 app expects.
5280 		 */
5281 		mtop_32_for_64.mt_op = local.mt_op;
5282 		mtop_32_for_64.mt_count = local.mt_count;
5283 
5284 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5285 		    sizeof (struct mtop32), flag)) {
5286 			rval = EFAULT;
5287 		}
5288 		break;
5289 
5290 	case DDI_MODEL_NONE:
5291 		passed.mt_count = local.mt_count;
5292 		passed.mt_op = local.mt_op;
5293 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5294 			rval = EFAULT;
5295 		}
5296 		break;
5297 	}
5298 #else /* ! _MULTI_DATAMODE */
5299 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5300 		rval = ERANGE;
5301 	} else {
5302 		passed.mt_op = local.mt_op;
5303 		passed.mt_count = local.mt_count;
5304 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5305 			rval = EFAULT;
5306 		}
5307 	}
5308 #endif /* _MULTI_DATAMODE */
5309 
5310 
5311 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5312 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5313 	    un->un_pos.blkno, un->un_pos.eof);
5314 
5315 	if (un->un_pos.pmode == invalid) {
5316 		un->un_density_known = 0;
5317 	}
5318 
5319 	ASSERT(mutex_owned(ST_MUTEX));
5320 	return (rval);
5321 }
5322 
5323 static int
5324 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5325 {
5326 	struct mtlop local;
5327 	int rval;
5328 
5329 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5330 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5331 		return (EFAULT);
5332 	}
5333 
5334 	rval = st_do_mtioctop(un, &local);
5335 
5336 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5337 		rval = EFAULT;
5338 	}
5339 	return (rval);
5340 }
5341 
5342 
5343 static int
5344 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5345 {
5346 	dev_t dev = un->un_dev;
5347 	int savefile;
5348 	int rval = 0;
5349 
5350 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5351 
5352 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5353 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5354 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5355 	    "fileno=%x, blkno=%x, eof=%x\n",
5356 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5357 
5358 	un->un_status = 0;
5359 
5360 	/*
5361 	 * if we are going to mess with a tape, we have to make sure we have
5362 	 * one and are not offline (i.e. no tape is initialized).  We let
5363 	 * commands pass here that don't actually touch the tape, except for
5364 	 * loading and initialization (rewinding).
5365 	 */
5366 	if (un->un_state == ST_STATE_OFFLINE) {
5367 		switch (mtop->mt_op) {
5368 		case MTLOAD:
5369 		case MTNOP:
5370 			/*
5371 			 * We don't want strategy calling st_tape_init here,
5372 			 * so, change state
5373 			 */
5374 			un->un_state = ST_STATE_INITIALIZING;
5375 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5376 			    "st_do_mtioctop : OFFLINE state = %d\n",
5377 			    un->un_state);
5378 			break;
5379 		default:
5380 			/*
5381 			 * reinitialize by normal means
5382 			 */
5383 			rval = st_tape_init(dev);
5384 			if (rval) {
5385 				un->un_state = ST_STATE_INITIALIZING;
5386 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5387 				    "st_do_mtioctop : OFFLINE init failure ");
5388 				un->un_state = ST_STATE_OFFLINE;
5389 				un->un_pos.pmode = invalid;
5390 				if (rval != EACCES) {
5391 					rval = EIO;
5392 				}
5393 				return (rval);
5394 			}
5395 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5396 			break;
5397 		}
5398 	}
5399 
5400 	/*
5401 	 * If the file position is invalid, allow only those
5402 	 * commands that properly position the tape and fail
5403 	 * the rest with EIO
5404 	 */
5405 	if (un->un_pos.pmode == invalid) {
5406 		switch (mtop->mt_op) {
5407 		case MTWEOF:
5408 		case MTRETEN:
5409 		case MTERASE:
5410 		case MTEOM:
5411 		case MTFSF:
5412 		case MTFSR:
5413 		case MTBSF:
5414 		case MTNBSF:
5415 		case MTBSR:
5416 		case MTSRSZ:
5417 		case MTGRSZ:
5418 		case MTSEEK:
5419 		case MTBSSF:
5420 		case MTFSSF:
5421 			return (EIO);
5422 			/* NOTREACHED */
5423 		case MTREW:
5424 		case MTLOAD:
5425 		case MTOFFL:
5426 		case MTNOP:
5427 		case MTTELL:
5428 		case MTLOCK:
5429 		case MTUNLOCK:
5430 			break;
5431 
5432 		default:
5433 			return (ENOTTY);
5434 			/* NOTREACHED */
5435 		}
5436 	}
5437 
5438 	switch (mtop->mt_op) {
5439 	case MTERASE:
5440 		/*
5441 		 * MTERASE rewinds the tape, erase it completely, and returns
5442 		 * to the beginning of the tape
5443 		 */
5444 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5445 			un->un_status = KEY_WRITE_PROTECT;
5446 			un->un_err_resid = mtop->mt_count;
5447 			COPY_POS(&un->un_err_pos, &un->un_pos);
5448 			return (EACCES);
5449 		}
5450 		if (un->un_dp->options & ST_REEL) {
5451 			un->un_fmneeded = 2;
5452 		} else {
5453 			un->un_fmneeded = 1;
5454 		}
5455 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5456 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
5457 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
5458 			un->un_pos.pmode = invalid;
5459 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5460 			    "st_do_mtioctop : EIO space or erase or "
5461 			    "check den)\n");
5462 			rval = EIO;
5463 		} else {
5464 			/* QIC and helical scan rewind after erase */
5465 			if (un->un_dp->options & ST_REEL) {
5466 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
5467 			}
5468 		}
5469 		break;
5470 
5471 	case MTWEOF:
5472 		/*
5473 		 * write an end-of-file record
5474 		 */
5475 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5476 			un->un_status = KEY_WRITE_PROTECT;
5477 			un->un_err_resid = mtop->mt_count;
5478 			COPY_POS(&un->un_err_pos, &un->un_pos);
5479 			return (EACCES);
5480 		}
5481 
5482 		/*
5483 		 * zero count means just flush buffers
5484 		 * negative count is not permitted
5485 		 */
5486 		if (mtop->mt_count < 0) {
5487 			return (EINVAL);
5488 		}
5489 
5490 		/* Not on worm */
5491 		if (un->un_read_only == RDWR) {
5492 			un->un_test_append = 1;
5493 		}
5494 
5495 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5496 			if (st_determine_density(dev, B_WRITE)) {
5497 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5498 				    "st_do_mtioctop : EIO : MTWEOF can't "
5499 				    "determine density");
5500 				return (EIO);
5501 			}
5502 		}
5503 
5504 		rval = st_write_fm(dev, (int)mtop->mt_count);
5505 		if ((rval != 0) && (rval != EACCES)) {
5506 			/*
5507 			 * Failure due to something other than illegal
5508 			 * request results in loss of state (st_intr).
5509 			 */
5510 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5511 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5512 			    "file mark");
5513 			rval = EIO;
5514 		}
5515 		break;
5516 
5517 	case MTRETEN:
5518 		/*
5519 		 * retension the tape
5520 		 */
5521 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5522 		    st_cmd(dev, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5523 			un->un_pos.pmode = invalid;
5524 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5525 			    "st_do_mtioctop : EIO : MTRETEN ");
5526 			rval = EIO;
5527 		}
5528 		break;
5529 
5530 	case MTREW:
5531 		/*
5532 		 * rewind  the tape
5533 		 */
5534 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5535 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5536 			    "st_do_mtioctop : EIO:MTREW check "
5537 			    "density/wfm failed");
5538 			return (EIO);
5539 		}
5540 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
5541 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5542 			    "st_do_mtioctop : EIO : MTREW ");
5543 			rval = EIO;
5544 		}
5545 		break;
5546 
5547 	case MTOFFL:
5548 		/*
5549 		 * rewinds, and, if appropriate, takes the device offline by
5550 		 * unloading the tape
5551 		 */
5552 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5553 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5554 			    "st_do_mtioctop :EIO:MTOFFL check "
5555 			    "density/wfm failed");
5556 			return (EIO);
5557 		}
5558 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
5559 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5560 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5561 			    "st_do_mtioctop : EIO : MTOFFL");
5562 			return (EIO);
5563 		}
5564 		un->un_pos.eof = ST_NO_EOF;
5565 		un->un_laststate = un->un_state;
5566 		un->un_state = ST_STATE_OFFLINE;
5567 		un->un_mediastate = MTIO_EJECTED;
5568 		break;
5569 
5570 	case MTLOAD:
5571 		/*
5572 		 * This is to load a tape into the drive
5573 		 * Note that if the tape is not loaded, the device will have
5574 		 * to be opened via O_NDELAY or O_NONBLOCK.
5575 		 */
5576 		/*
5577 		 * Let's try and clean things up, if we are not
5578 		 * initializing, and then send in the load command, no
5579 		 * matter what.
5580 		 *
5581 		 * load after a media change by the user.
5582 		 */
5583 
5584 		if (un->un_state > ST_STATE_INITIALIZING) {
5585 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5586 		}
5587 		rval = st_cmd(dev, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5588 		/* Load command to a drive that doesn't support load */
5589 		if ((rval == EIO) &&
5590 		    ((un->un_status == KEY_NOT_READY) &&
5591 			/* Medium not present */
5592 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5593 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5594 		    (un->un_dp->type == MT_ISSTK9840) &&
5595 			/* CSL not present */
5596 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5597 			rval = ENOTTY;
5598 			break;
5599 		} else if (rval != EACCES) {
5600 			rval = EIO;
5601 		}
5602 		if (rval) {
5603 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5604 			    "st_do_mtioctop : %s : MTLOAD\n",
5605 			    rval == EACCES ? "EACCES" : "EIO");
5606 			/*
5607 			 * If load tape fails, who knows what happened...
5608 			 */
5609 			un->un_pos.pmode = invalid;
5610 			break;
5611 		}
5612 
5613 		/*
5614 		 * reset all counters appropriately using rewind, as if LOAD
5615 		 * succeeds, we are at BOT
5616 		 */
5617 		un->un_state = ST_STATE_INITIALIZING;
5618 
5619 		rval = st_tape_init(dev);
5620 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5621 			rval = 0;
5622 			break;
5623 		}
5624 
5625 		if (rval != 0) {
5626 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5627 			    "st_do_mtioctop : EIO : MTLOAD calls "
5628 			    "st_tape_init\n");
5629 			rval = EIO;
5630 			un->un_state = ST_STATE_OFFLINE;
5631 		}
5632 
5633 		break;
5634 
5635 	case MTNOP:
5636 		un->un_status = 0;		/* Reset status */
5637 		un->un_err_resid = 0;
5638 		mtop->mt_count = MTUNIT(dev);
5639 		break;
5640 
5641 	case MTEOM:
5642 		/*
5643 		 * positions the tape at a location just after the last file
5644 		 * written on the tape. For cartridge and 8 mm, this after
5645 		 * the last file mark; for reel, this is inbetween the two
5646 		 * last 2 file marks
5647 		 */
5648 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5649 		    (un->un_lastop == ST_OP_WRITE) ||
5650 		    (un->un_lastop == ST_OP_WEOF)) {
5651 			/*
5652 			 * If the command wants to move to logical end
5653 			 * of media, and we're already there, we're done.
5654 			 * If we were at logical eot, we reset the state
5655 			 * to be *not* at logical eot.
5656 			 *
5657 			 * If we're at physical or logical eot, we prohibit
5658 			 * forward space operations (unconditionally).
5659 			 *
5660 			 * Also if the last operation was a write of any
5661 			 * kind the tape is at EOD.
5662 			 */
5663 			return (0);
5664 		}
5665 		/*
5666 		 * physical tape position may not be what we've been
5667 		 * telling the user; adjust the request accordingly
5668 		 */
5669 		if (IN_EOF(un->un_pos)) {
5670 			un->un_pos.fileno++;
5671 			un->un_pos.blkno = 0;
5672 		}
5673 
5674 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5675 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5676 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5677 			    " failed");
5678 			return (EIO);
5679 		}
5680 
5681 		/*
5682 		 * st_find_eod() returns the last fileno we knew about;
5683 		 */
5684 		savefile = st_find_eod(dev);
5685 
5686 		if ((un->un_status != KEY_BLANK_CHECK) &&
5687 		    (un->un_status != SUN_KEY_EOT)) {
5688 			un->un_pos.pmode = invalid;
5689 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5690 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5691 			rval = EIO;
5692 		} else {
5693 			/*
5694 			 * For 1/2" reel tapes assume logical EOT marked
5695 			 * by two file marks or we don't care that we may
5696 			 * be extending the last file on the tape.
5697 			 */
5698 			if (un->un_dp->options & ST_REEL) {
5699 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
5700 				    SYNC_CMD)) {
5701 					un->un_pos.pmode = invalid;
5702 					ST_DEBUG2(ST_DEVINFO, st_label,
5703 					    SCSI_DEBUG,
5704 					    "st_do_mtioctop : EIO : MTEOM space"
5705 					    " cmd failed");
5706 					rval = EIO;
5707 					break;
5708 				}
5709 				/*
5710 				 * Fix up the block number.
5711 				 */
5712 				un->un_pos.blkno = 0;
5713 				un->un_err_pos.blkno = 0;
5714 			}
5715 			un->un_err_resid = 0;
5716 			un->un_pos.fileno = savefile;
5717 			un->un_pos.eof = ST_EOT;
5718 		}
5719 		un->un_status = 0;
5720 		break;
5721 
5722 	case MTFSF:
5723 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5724 		break;
5725 
5726 	case MTFSR:
5727 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5728 		break;
5729 
5730 	case MTBSF:
5731 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5732 		break;
5733 
5734 	case MTNBSF:
5735 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5736 		break;
5737 
5738 	case MTBSR:
5739 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5740 		break;
5741 
5742 	case MTBSSF:
5743 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5744 		break;
5745 
5746 	case MTFSSF:
5747 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5748 		break;
5749 
5750 	case MTSRSZ:
5751 
5752 		/*
5753 		 * Set record-size to that sent by user
5754 		 * Check to see if there is reason that the requested
5755 		 * block size should not be set.
5756 		 */
5757 
5758 		/* If requesting variable block size is it ok? */
5759 		if ((mtop->mt_count == 0) &&
5760 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5761 			return (ENOTTY);
5762 		}
5763 
5764 		/*
5765 		 * If requested block size is not variable "0",
5766 		 * is it less then minimum.
5767 		 */
5768 		if ((mtop->mt_count != 0) &&
5769 		    (mtop->mt_count < un->un_minbsize)) {
5770 			return (EINVAL);
5771 		}
5772 
5773 		/* Is the requested block size more then maximum */
5774 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5775 		    (un->un_maxbsize != 0)) {
5776 			return (EINVAL);
5777 		}
5778 
5779 		/* Is requested block size a modulus the device likes */
5780 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5781 			return (EINVAL);
5782 		}
5783 
5784 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5785 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5786 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5787 			return (EIO);
5788 		}
5789 
5790 		return (0);
5791 
5792 	case MTGRSZ:
5793 		/*
5794 		 * Get record-size to the user
5795 		 */
5796 		mtop->mt_count = un->un_bsize;
5797 		rval = 0;
5798 		break;
5799 
5800 	case MTTELL:
5801 		rval = st_update_block_pos(un);
5802 		mtop->mt_count = un->un_pos.lgclblkno;
5803 		break;
5804 
5805 	case MTSEEK:
5806 		rval = st_logical_block_locate(un, (uint64_t)mtop->mt_count,
5807 		    un->un_pos.partition);
5808 		/*
5809 		 * This bit of magic make mt print the actual position if
5810 		 * the resulting position was not what was asked for.
5811 		 */
5812 		if (rval == ESPIPE) {
5813 			rval = EIO;
5814 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
5815 				mtop->mt_op = MTTELL;
5816 				mtop->mt_count = un->un_pos.lgclblkno;
5817 			}
5818 		}
5819 		break;
5820 
5821 	case MTLOCK:
5822 		if (st_cmd(dev, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
5823 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5824 			    "st_do_mtioctop : EIO : MTLOCK");
5825 			rval = EIO;
5826 		}
5827 		break;
5828 
5829 	case MTUNLOCK:
5830 		if (st_cmd(dev, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
5831 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5832 			    "st_do_mtioctop : EIO : MTUNLOCK");
5833 			rval = EIO;
5834 		}
5835 		break;
5836 
5837 	default:
5838 		rval = ENOTTY;
5839 	}
5840 
5841 	return (rval);
5842 }
5843 
5844 
5845 /*
5846  * Run a command for uscsi ioctl.
5847  */
5848 static int
5849 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd, int flag)
5850 {
5851 	struct uscsi_cmd	*uscmd;
5852 	struct buf	*bp;
5853 	enum uio_seg	uioseg;
5854 	int	offline_state = 0;
5855 	int	err = 0;
5856 
5857 	GET_SOFT_STATE(dev);
5858 
5859 	ST_FUNC(ST_DEVINFO, st_ioctl_cmd);
5860 
5861 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5862 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5863 
5864 	ASSERT(mutex_owned(ST_MUTEX));
5865 
5866 	/*
5867 	 * We really don't know what commands are coming in here and
5868 	 * we don't want to limit the commands coming in.
5869 	 *
5870 	 * If st_tape_init() gets called from st_strategy(), then we
5871 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5872 	 * which it never will, as we set it below.  To prevent
5873 	 * st_tape_init() from getting called, we have to set state to other
5874 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5875 	 * achieves this purpose already.
5876 	 *
5877 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5878 	 * so other entry points to the driver might have the chance to call
5879 	 * st_tape_init().
5880 	 */
5881 	if (un->un_state == ST_STATE_OFFLINE) {
5882 		un->un_laststate = ST_STATE_OFFLINE;
5883 		un->un_state = ST_STATE_INITIALIZING;
5884 		offline_state = 1;
5885 	}
5886 
5887 	mutex_exit(ST_MUTEX);
5888 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag,
5889 	    ROUTE, &uscmd);
5890 	mutex_enter(ST_MUTEX);
5891 	if (err != 0) {
5892 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5893 		    "st_ioctl_cmd: scsi_uscsi_alloc_and_copyin failed\n");
5894 		goto exit;
5895 	}
5896 
5897 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
5898 
5899 	/* check to see if this command requires the drive to be reserved */
5900 	if (uscmd->uscsi_cdb != NULL) {
5901 		err = st_check_cdb_for_need_to_reserve(un,
5902 		    &((char *)uscmd->uscsi_cdb)[0]);
5903 		if (err) {
5904 			goto exit_free;
5905 		}
5906 	}
5907 
5908 	/*
5909 	 * Get buffer resources...
5910 	 */
5911 	while (un->un_sbuf_busy)
5912 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5913 	un->un_sbuf_busy = 1;
5914 
5915 #ifdef STDEBUG
5916 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0xf) > 6) {
5917 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5918 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5919 		    "uscsi cdb", uscmd->uscsi_cdb);
5920 		if (uscmd->uscsi_buflen) {
5921 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5922 			    "uscsi %s of %ld bytes %s %s space\n",
5923 			    (rw == B_READ) ? rd_str : wr_str,
5924 			    uscmd->uscsi_buflen,
5925 			    (rw == B_READ) ? "to" : "from",
5926 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
5927 		}
5928 	}
5929 #endif /* ST_DEBUG */
5930 
5931 	/*
5932 	 * Although st_ioctl_cmd() never makes use of these
5933 	 * now, we are just being safe and consistent.
5934 	 */
5935 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
5936 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
5937 
5938 	un->un_srqbufp = uscmd->uscsi_rqbuf;
5939 	bp = un->un_sbufp;
5940 	bzero(bp, sizeof (buf_t));
5941 	if (uscmd->uscsi_cdb != NULL) {
5942 		bp->b_forw =
5943 		    (struct buf *)(uintptr_t)((char *)uscmd->uscsi_cdb)[0];
5944 		bp->b_back = (struct buf *)uscmd;
5945 	}
5946 
5947 	mutex_exit(ST_MUTEX);
5948 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd,
5949 	    st_strategy, bp, NULL);
5950 	mutex_enter(ST_MUTEX);
5951 
5952 	/*
5953 	 * If scsi reset successful, don't write any filemarks.
5954 	 */
5955 	if ((err == 0) && (uscmd->uscsi_flags &
5956 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
5957 		un->un_fmneeded = 0;
5958 	}
5959 
5960 exit_free:
5961 	/*
5962 	 * Free resources
5963 	 */
5964 	un->un_sbuf_busy = 0;
5965 	un->un_srqbufp = NULL;
5966 
5967 	/*
5968 	 * If was a space command need to update logical block position.
5969 	 * If the command failed such that positioning is invalid, Don't
5970 	 * update the position as the user must do this to validate the
5971 	 * position for data protection.
5972 	 */
5973 	if ((uscmd->uscsi_cdb != NULL) &&
5974 	    (uscmd->uscsi_cdb[0] == SCMD_SPACE) &&
5975 	    (un->un_pos.pmode != invalid)) {
5976 		uchar_t status = un->un_status;
5977 		(void) st_update_block_pos(un);
5978 		un->un_status = status;
5979 	}
5980 	cv_signal(&un->un_sbuf_cv);
5981 	mutex_exit(ST_MUTEX);
5982 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
5983 	mutex_enter(ST_MUTEX);
5984 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5985 	    "st_ioctl_cmd returns 0x%x\n", err);
5986 
5987 exit:
5988 	/* don't lose offline state */
5989 	if (offline_state) {
5990 		un->un_state = ST_STATE_OFFLINE;
5991 	}
5992 
5993 	ASSERT(mutex_owned(ST_MUTEX));
5994 	return (err);
5995 }
5996 
5997 static int
5998 st_write_fm(dev_t dev, int wfm)
5999 {
6000 	int i;
6001 	int rval;
6002 
6003 	GET_SOFT_STATE(dev);
6004 
6005 	ST_FUNC(ST_DEVINFO, st_write_fm);
6006 
6007 	ASSERT(mutex_owned(ST_MUTEX));
6008 
6009 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6010 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6011 
6012 	/*
6013 	 * write one filemark at the time after EOT
6014 	 */
6015 	if (un->un_pos.eof >= ST_EOT) {
6016 		for (i = 0; i < wfm; i++) {
6017 			rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6018 			if (rval == EACCES) {
6019 				return (rval);
6020 			}
6021 			if (rval != 0) {
6022 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6023 				    "st_write_fm : EIO : write EOT file mark");
6024 				return (EIO);
6025 			}
6026 		}
6027 	} else {
6028 		rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6029 		if (rval == EACCES) {
6030 			return (rval);
6031 		}
6032 		if (rval) {
6033 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6034 			    "st_write_fm : EIO : write file mark");
6035 			return (EIO);
6036 		}
6037 	}
6038 
6039 	ASSERT(mutex_owned(ST_MUTEX));
6040 	return (0);
6041 }
6042 
6043 #ifdef STDEBUG
6044 static void
6045 start_dump(struct scsi_tape *un, struct buf *bp)
6046 {
6047 	struct scsi_pkt *pkt = BP_PKT(bp);
6048 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6049 
6050 	ST_FUNC(ST_DEVINFO, start_dump);
6051 
6052 	if ((st_debug & 0xf) < 6)
6053 		return;
6054 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6055 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6056 	    (void *)bp->b_forw, bp->b_bcount,
6057 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6058 
6059 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6060 	    "st_start: cdb",  (caddr_t)cdbp);
6061 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6062 	    "st_start: fileno=%d, blk=%d\n",
6063 	    un->un_pos.fileno, un->un_pos.blkno);
6064 }
6065 #endif
6066 
6067 
6068 /*
6069  * Command start && done functions
6070  */
6071 
6072 /*
6073  * st_start()
6074  *
6075  * Called from:
6076  *  st_strategy() to start a command.
6077  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6078  *  st_attach() when resuming from power down state.
6079  *  st_start_restart() to retry transport when device was previously busy.
6080  *  st_done_and_mutex_exit() to start the next command when previous is done.
6081  *
6082  * On entry:
6083  *  scsi_pkt may or may not be allocated.
6084  *
6085  */
6086 static void
6087 st_start(struct scsi_tape *un)
6088 {
6089 	struct buf *bp;
6090 	int status;
6091 
6092 	ST_FUNC(ST_DEVINFO, st_start);
6093 	ASSERT(mutex_owned(ST_MUTEX));
6094 
6095 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6096 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6097 
6098 	if ((bp = un->un_quef) == NULL) {
6099 		return;
6100 	}
6101 
6102 	ASSERT((bp->b_flags & B_DONE) == 0);
6103 
6104 	/*
6105 	 * Don't send more than un_throttle commands to the HBA
6106 	 */
6107 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6108 		return;
6109 	}
6110 
6111 	/*
6112 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6113 	 * build the command.
6114 	 */
6115 	if (BP_PKT(bp) == NULL) {
6116 		ASSERT((bp->b_flags & B_DONE) == 0);
6117 		st_make_cmd(un, bp, st_runout);
6118 		ASSERT((bp->b_flags & B_DONE) == 0);
6119 		status = geterror(bp);
6120 
6121 		/*
6122 		 * Some HBA's don't call bioerror() to set an error.
6123 		 * And geterror() returns zero if B_ERROR is not set.
6124 		 * So if we get zero we must check b_error.
6125 		 */
6126 		if (status == 0 && bp->b_error != 0) {
6127 			status = bp->b_error;
6128 			bioerror(bp, status);
6129 		}
6130 
6131 		/*
6132 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6133 		 * In tape ENOMEM has special meaning so we'll change it.
6134 		 */
6135 		if (status == ENOMEM) {
6136 			status = 0;
6137 			bioerror(bp, status);
6138 		}
6139 
6140 		/*
6141 		 * Did it fail and is it retryable?
6142 		 * If so return and wait for the callback through st_runout.
6143 		 * Also looks like scsi_init_pkt() will setup a callback even
6144 		 * if it isn't retryable.
6145 		 */
6146 		if (BP_PKT(bp) == NULL) {
6147 			if (status == 0) {
6148 				/*
6149 				 * If first attempt save state.
6150 				 */
6151 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6152 					un->un_laststate = un->un_state;
6153 					un->un_state = ST_STATE_RESOURCE_WAIT;
6154 				}
6155 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6156 				    "temp no resources for pkt\n");
6157 			} else {
6158 				/*
6159 				 * Unlikely that it would be retryable then not.
6160 				 */
6161 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6162 					un->un_state = un->un_laststate;
6163 				}
6164 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6165 				    "perm no resources for pkt errno = 0x%x\n",
6166 				    status);
6167 			}
6168 			return;
6169 		}
6170 		/*
6171 		 * Worked this time set the state back.
6172 		 */
6173 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6174 			un->un_state = un->un_laststate;
6175 		}
6176 	}
6177 
6178 	/*
6179 	 * move from waitq to runq
6180 	 */
6181 	un->un_quef = bp->b_actf;
6182 	if (un->un_quel == bp) {
6183 		/*
6184 		 *  For the case of queue having one
6185 		 *  element, set the tail pointer to
6186 		 *  point to the element.
6187 		 */
6188 		un->un_quel = bp->b_actf;
6189 	}
6190 
6191 	bp->b_actf = NULL;
6192 
6193 	if (un->un_runqf) {
6194 		un->un_runql->b_actf = bp;
6195 	} else {
6196 		un->un_runqf = bp;
6197 	}
6198 	un->un_runql = bp;
6199 
6200 
6201 	ST_CDB(ST_DEVINFO, "Start CDB", (char *)BP_PKT(bp)->pkt_cdbp);
6202 
6203 #ifdef STDEBUG
6204 	start_dump(un, bp);
6205 #endif
6206 
6207 	/* could not get here if throttle was zero */
6208 	un->un_last_throttle = un->un_throttle;
6209 	un->un_throttle = 0;	/* so nothing else will come in here */
6210 	un->un_ncmds++;
6211 
6212 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6213 
6214 	mutex_exit(ST_MUTEX);
6215 
6216 	status = scsi_transport(BP_PKT(bp));
6217 
6218 	mutex_enter(ST_MUTEX);
6219 
6220 	if (un->un_last_throttle) {
6221 		un->un_throttle = un->un_last_throttle;
6222 	}
6223 
6224 	if (status != TRAN_ACCEPT) {
6225 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6226 		mutex_exit(ST_MUTEX);
6227 
6228 		if (status == TRAN_BUSY) {
6229 			/* if too many retries, fail the transport */
6230 			if (st_handle_start_busy(un, bp,
6231 			    ST_TRAN_BUSY_TIMEOUT) == 0)
6232 				goto done;
6233 		}
6234 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6235 		    "transport rejected\n");
6236 		bp->b_resid = bp->b_bcount;
6237 
6238 
6239 #ifndef __lock_lint
6240 		/*
6241 		 * warlock doesn't understand this potential
6242 		 * recursion?
6243 		 */
6244 		mutex_enter(ST_MUTEX);
6245 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6246 		ST_DO_ERRSTATS(un, st_transerrs);
6247 		st_bioerror(bp, EIO);
6248 		SET_PE_FLAG(un);
6249 		st_done_and_mutex_exit(un, bp);
6250 #endif
6251 	} else {
6252 		un->un_tran_retry_ct = 0;
6253 		mutex_exit(ST_MUTEX);
6254 	}
6255 
6256 done:
6257 
6258 	mutex_enter(ST_MUTEX);
6259 }
6260 
6261 /*
6262  * if the transport is busy, then put this bp back on the waitq
6263  */
6264 static int
6265 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6266     clock_t timeout_interval)
6267 {
6268 	struct buf *last_quef, *runq_bp;
6269 	int rval = 0;
6270 
6271 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6272 
6273 	mutex_enter(ST_MUTEX);
6274 
6275 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6276 	    "st_handle_start_busy()\n");
6277 
6278 	/*
6279 	 * Check to see if we hit the retry timeout and one last check for
6280 	 * making sure this is the last on the runq, if it is not, we have
6281 	 * to fail
6282 	 */
6283 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6284 	    (un->un_runql != bp)) {
6285 		rval = -1;
6286 		goto exit;
6287 	}
6288 
6289 	/* put the bp back on the waitq */
6290 	if (un->un_quef) {
6291 		last_quef = un->un_quef;
6292 		un->un_quef = bp;
6293 		bp->b_actf = last_quef;
6294 	} else  {
6295 		bp->b_actf = NULL;
6296 		un->un_quef = bp;
6297 		un->un_quel = bp;
6298 	}
6299 
6300 	/*
6301 	 * Decrement un_ncmds so that this
6302 	 * gets thru' st_start() again.
6303 	 */
6304 	un->un_ncmds--;
6305 
6306 	/*
6307 	 * since this is an error case, we won't have to do
6308 	 * this list walking much.  We've already made sure this bp was the
6309 	 * last on the runq
6310 	 */
6311 	runq_bp = un->un_runqf;
6312 
6313 	if (un->un_runqf == bp) {
6314 		un->un_runqf = NULL;
6315 		un->un_runql = NULL;
6316 	} else {
6317 		while (runq_bp) {
6318 			if (runq_bp->b_actf == bp) {
6319 				runq_bp->b_actf = NULL;
6320 				un->un_runql = runq_bp;
6321 				break;
6322 			}
6323 			runq_bp = runq_bp->b_actf;
6324 		}
6325 	}
6326 
6327 
6328 	/*
6329 	 * send a marker pkt, if appropriate
6330 	 */
6331 	st_hba_unflush(un);
6332 
6333 	/*
6334 	 * all queues are aligned, we are just waiting to
6335 	 * transport, don't alloc any more buf p's, when
6336 	 * st_start is reentered.
6337 	 */
6338 	(void) timeout(st_start_restart, un, timeout_interval);
6339 
6340 exit:
6341 	mutex_exit(ST_MUTEX);
6342 	return (rval);
6343 }
6344 
6345 
6346 /*
6347  * st_runout a callback that is called what a resource allocatation failed
6348  */
6349 static int
6350 st_runout(caddr_t arg)
6351 {
6352 	struct scsi_tape *un = (struct scsi_tape *)arg;
6353 	struct buf *bp;
6354 	ASSERT(un != NULL);
6355 
6356 	ST_FUNC(ST_DEVINFO, st_runout);
6357 
6358 	mutex_enter(ST_MUTEX);
6359 
6360 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6361 
6362 	bp = un->un_quef;
6363 
6364 	/*
6365 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6366 	 */
6367 	if ((bp != NULL) && (geterror(bp) != 0)) {
6368 
6369 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6370 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6371 		    bp->b_flags, geterror(bp));
6372 		ASSERT((bp->b_flags & B_DONE) == 0);
6373 
6374 		un->un_quef = bp->b_actf;
6375 		if (un->un_quel == bp) {
6376 			/*
6377 			 *  For the case of queue having one
6378 			 *  element, set the tail pointer to
6379 			 *  point to the element.
6380 			 */
6381 			un->un_quel = bp->b_actf;
6382 		}
6383 		mutex_exit(ST_MUTEX);
6384 		bp->b_actf = NULL;
6385 
6386 		ASSERT((bp->b_flags & B_DONE) == 0);
6387 
6388 		/*
6389 		 * Set resid, Error already set, then unblock calling thread.
6390 		 */
6391 		bp->b_resid = bp->b_bcount;
6392 		biodone(bp);
6393 	} else {
6394 		/*
6395 		 * Try Again
6396 		 */
6397 		st_start(un);
6398 		mutex_exit(ST_MUTEX);
6399 	}
6400 
6401 	/*
6402 	 * Comments courtesy of sd.c
6403 	 * The scsi_init_pkt routine allows for the callback function to
6404 	 * return a 0 indicating the callback should be rescheduled or a 1
6405 	 * indicating not to reschedule. This routine always returns 1
6406 	 * because the driver always provides a callback function to
6407 	 * scsi_init_pkt. This results in a callback always being scheduled
6408 	 * (via the scsi_init_pkt callback implementation) if a resource
6409 	 * failure occurs.
6410 	 */
6411 
6412 	return (1);
6413 }
6414 
6415 /*
6416  * st_done_and_mutex_exit()
6417  *	- remove bp from runq
6418  *	- start up the next request
6419  *	- if this was an asynch bp, clean up
6420  *	- exit with released mutex
6421  */
6422 static void
6423 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6424 {
6425 	struct buf *runqbp, *prevbp;
6426 	int	pe_flagged = 0;
6427 
6428 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6429 #if !defined(lint)
6430 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6431 #endif
6432 
6433 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6434 
6435 	ASSERT(mutex_owned(ST_MUTEX));
6436 
6437 	/*
6438 	 * if bp is still on the runq (anywhere), then remove it
6439 	 */
6440 	prevbp = NULL;
6441 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
6442 		if (runqbp == bp) {
6443 			if (runqbp == un->un_runqf) {
6444 				un->un_runqf = bp->b_actf;
6445 			} else {
6446 				prevbp->b_actf = bp->b_actf;
6447 			}
6448 			if (un->un_runql == bp) {
6449 				un->un_runql = prevbp;
6450 			}
6451 			break;
6452 		}
6453 		prevbp = runqbp;
6454 	}
6455 	bp->b_actf = NULL;
6456 
6457 	un->un_ncmds--;
6458 	cv_signal(&un->un_queue_cv);
6459 
6460 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6461 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6462 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
6463 	    bp->b_resid, bp->b_flags);
6464 
6465 
6466 	/*
6467 	 * update kstats with transfer count info
6468 	 */
6469 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6470 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6471 		if (bp->b_flags & B_READ) {
6472 			IOSP->reads++;
6473 			IOSP->nread += n_done;
6474 		} else {
6475 			IOSP->writes++;
6476 			IOSP->nwritten += n_done;
6477 		}
6478 	}
6479 
6480 	/*
6481 	 * Start the next one before releasing resources on this one, if
6482 	 * there is something on the queue and persistent errors has not been
6483 	 * flagged
6484 	 */
6485 
6486 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
6487 		un->un_last_resid = bp->b_resid;
6488 		un->un_last_count = bp->b_bcount;
6489 	}
6490 
6491 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6492 		cv_broadcast(&un->un_tape_busy_cv);
6493 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
6494 		st_start(un);
6495 	}
6496 
6497 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6498 		/*
6499 		 * Since we marked this ourselves as ASYNC,
6500 		 * there isn't anybody around waiting for
6501 		 * completion any more.
6502 		 */
6503 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
6504 		if (com == SCMD_READ || com == SCMD_WRITE) {
6505 			bp->b_un.b_addr = (caddr_t)0;
6506 		}
6507 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6508 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6509 		scsi_destroy_pkt(BP_PKT(bp));
6510 		un->un_sbuf_busy = 0;
6511 		cv_signal(&un->un_sbuf_cv);
6512 		mutex_exit(ST_MUTEX);
6513 		return;
6514 	}
6515 
6516 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6517 		/*
6518 		 * Copy status from scsi_pkt to uscsi_cmd
6519 		 * since st_ioctl_cmd needs it
6520 		 */
6521 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6522 	}
6523 
6524 
6525 #ifdef STDEBUG
6526 	if (((st_debug & 0xf) >= 4) &&
6527 	    (((un->un_pos.blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
6528 
6529 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6530 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6531 		    "un_errno = %d, un_pe = %d\n",
6532 		    un->un_ncmds, un->un_throttle, un->un_errno,
6533 		    un->un_persist_errors);
6534 	}
6535 
6536 #endif
6537 
6538 	mutex_exit(ST_MUTEX);
6539 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6540 	    "st_done_and_mutex_exit: freeing pkt\n");
6541 
6542 	scsi_destroy_pkt(BP_PKT(bp));
6543 
6544 	biodone(bp);
6545 
6546 	/*
6547 	 * now that we biodoned that command, if persistent errors have been
6548 	 * flagged, flush the waitq
6549 	 */
6550 	if (pe_flagged)
6551 		st_flush(un);
6552 }
6553 
6554 
6555 /*
6556  * Tape error, flush tape driver queue.
6557  */
6558 static void
6559 st_flush(struct scsi_tape *un)
6560 {
6561 	struct buf *bp;
6562 
6563 	ST_FUNC(ST_DEVINFO, st_flush);
6564 
6565 	mutex_enter(ST_MUTEX);
6566 
6567 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6568 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6569 	    un->un_ncmds, (void *)un->un_quef);
6570 
6571 	/*
6572 	 * if we still have commands outstanding, wait for them to come in
6573 	 * before flushing the queue, and make sure there is a queue
6574 	 */
6575 	if (un->un_ncmds || !un->un_quef)
6576 		goto exit;
6577 
6578 	/*
6579 	 * we have no more commands outstanding, so let's deal with special
6580 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6581 	 * is 0, then we know there was no error and we return a 0 read or
6582 	 * write before showing errors
6583 	 */
6584 
6585 	/* Flush the wait queue. */
6586 	while ((bp = un->un_quef) != NULL) {
6587 		un->un_quef = bp->b_actf;
6588 
6589 		bp->b_resid = bp->b_bcount;
6590 
6591 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6592 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6593 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6594 
6595 		st_set_pe_errno(un);
6596 
6597 		bioerror(bp, un->un_errno);
6598 
6599 		mutex_exit(ST_MUTEX);
6600 		/* it should have one, but check anyway */
6601 		if (BP_PKT(bp)) {
6602 			scsi_destroy_pkt(BP_PKT(bp));
6603 		}
6604 		biodone(bp);
6605 		mutex_enter(ST_MUTEX);
6606 	}
6607 
6608 	/*
6609 	 * It's not a bad practice to reset the
6610 	 * waitq tail pointer to NULL.
6611 	 */
6612 	un->un_quel = NULL;
6613 
6614 exit:
6615 	/* we mucked with the queue, so let others know about it */
6616 	cv_signal(&un->un_queue_cv);
6617 	mutex_exit(ST_MUTEX);
6618 }
6619 
6620 
6621 /*
6622  * Utility functions
6623  */
6624 static int
6625 st_determine_generic(dev_t dev)
6626 {
6627 	int bsize;
6628 	static char *cart = "0.25 inch cartridge";
6629 	char *sizestr;
6630 
6631 	GET_SOFT_STATE(dev);
6632 
6633 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6634 
6635 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6636 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6637 
6638 	ASSERT(mutex_owned(ST_MUTEX));
6639 
6640 	if (st_modesense(un)) {
6641 		return (-1);
6642 	}
6643 
6644 	bsize = (un->un_mspl->high_bl << 16)	|
6645 	    (un->un_mspl->mid_bl << 8)	|
6646 	    (un->un_mspl->low_bl);
6647 
6648 	if (bsize == 0) {
6649 		un->un_dp->options |= ST_VARIABLE;
6650 		un->un_dp->bsize = 0;
6651 		un->un_bsize = 0;
6652 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6653 		/*
6654 		 * record size of this device too big.
6655 		 * try and convert it to variable record length.
6656 		 *
6657 		 */
6658 		un->un_dp->options |= ST_VARIABLE;
6659 		if (st_change_block_size(dev, 0) != 0) {
6660 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6661 			    "Fixed Record Size %d is too large\n", bsize);
6662 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6663 			    "Cannot switch to variable record size\n");
6664 			un->un_dp->options &= ~ST_VARIABLE;
6665 			return (-1);
6666 		}
6667 	} else if (st_change_block_size(dev, 0) == 0) {
6668 		/*
6669 		 * If the drive was set to a non zero block size,
6670 		 * See if it can be set to a zero block size.
6671 		 * If it works, ST_VARIABLE so user can set it as they want.
6672 		 */
6673 		un->un_dp->options |= ST_VARIABLE;
6674 		un->un_dp->bsize = 0;
6675 		un->un_bsize = 0;
6676 	} else {
6677 		un->un_dp->bsize = bsize;
6678 		un->un_bsize = bsize;
6679 	}
6680 
6681 
6682 	switch (un->un_mspl->density) {
6683 	default:
6684 	case 0x0:
6685 		/*
6686 		 * default density, cannot determine any other
6687 		 * information.
6688 		 */
6689 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6690 		un->un_dp->type = ST_TYPE_DEFAULT;
6691 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6692 		break;
6693 	case 0x1:
6694 	case 0x2:
6695 	case 0x3:
6696 	case 0x6:
6697 		/*
6698 		 * 1/2" reel
6699 		 */
6700 		sizestr = "0.50 inch reel";
6701 		un->un_dp->type = ST_TYPE_REEL;
6702 		un->un_dp->options |= ST_REEL;
6703 		un->un_dp->densities[0] = 0x1;
6704 		un->un_dp->densities[1] = 0x2;
6705 		un->un_dp->densities[2] = 0x6;
6706 		un->un_dp->densities[3] = 0x3;
6707 		break;
6708 	case 0x4:
6709 	case 0x5:
6710 	case 0x7:
6711 	case 0x0b:
6712 
6713 		/*
6714 		 * Quarter inch.
6715 		 */
6716 		sizestr = cart;
6717 		un->un_dp->type = ST_TYPE_DEFAULT;
6718 		un->un_dp->options |= ST_QIC;
6719 
6720 		un->un_dp->densities[1] = 0x4;
6721 		un->un_dp->densities[2] = 0x5;
6722 		un->un_dp->densities[3] = 0x7;
6723 		un->un_dp->densities[0] = 0x0b;
6724 		break;
6725 
6726 	case 0x0f:
6727 	case 0x10:
6728 	case 0x11:
6729 	case 0x12:
6730 		/*
6731 		 * QIC-120, QIC-150, QIC-320, QIC-600
6732 		 */
6733 		sizestr = cart;
6734 		un->un_dp->type = ST_TYPE_DEFAULT;
6735 		un->un_dp->options |= ST_QIC;
6736 		un->un_dp->densities[0] = 0x0f;
6737 		un->un_dp->densities[1] = 0x10;
6738 		un->un_dp->densities[2] = 0x11;
6739 		un->un_dp->densities[3] = 0x12;
6740 		break;
6741 
6742 	case 0x09:
6743 	case 0x0a:
6744 	case 0x0c:
6745 	case 0x0d:
6746 		/*
6747 		 * 1/2" cartridge tapes. Include HI-TC.
6748 		 */
6749 		sizestr = cart;
6750 		sizestr[2] = '5';
6751 		sizestr[3] = '0';
6752 		un->un_dp->type = ST_TYPE_HIC;
6753 		un->un_dp->densities[0] = 0x09;
6754 		un->un_dp->densities[1] = 0x0a;
6755 		un->un_dp->densities[2] = 0x0c;
6756 		un->un_dp->densities[3] = 0x0d;
6757 		break;
6758 
6759 	case 0x13:
6760 			/* DDS-2/DDS-3 scsi spec densities */
6761 	case 0x24:
6762 	case 0x25:
6763 	case 0x26:
6764 		sizestr = "DAT Data Storage (DDS)";
6765 		un->un_dp->type = ST_TYPE_DAT;
6766 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6767 		break;
6768 
6769 	case 0x14:
6770 		/*
6771 		 * Helical Scan (Exabyte) devices
6772 		 */
6773 		sizestr = "8mm helical scan cartridge";
6774 		un->un_dp->type = ST_TYPE_EXABYTE;
6775 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6776 		break;
6777 	}
6778 
6779 	/*
6780 	 * Assume LONG ERASE, BSF and BSR
6781 	 */
6782 
6783 	un->un_dp->options |=
6784 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6785 
6786 	/*
6787 	 * Only if mode sense data says no buffered write, set NOBUF
6788 	 */
6789 	if (un->un_mspl->bufm == 0)
6790 		un->un_dp->options |= ST_NOBUF;
6791 
6792 	/*
6793 	 * set up large read and write retry counts
6794 	 */
6795 
6796 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6797 
6798 	/*
6799 	 * If this is a 0.50 inch reel tape, and
6800 	 * it is *not* variable mode, try and
6801 	 * set it to variable record length
6802 	 * mode.
6803 	 */
6804 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6805 	    (un->un_dp->options & ST_VARIABLE)) {
6806 		if (st_change_block_size(dev, 0) == 0) {
6807 			un->un_dp->bsize = 0;
6808 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6809 			    un->un_mspl->low_bl = 0;
6810 		}
6811 	}
6812 
6813 	/*
6814 	 * Write to console about type of device found
6815 	 */
6816 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6817 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6818 	    sizestr);
6819 	if (un->un_dp->options & ST_VARIABLE) {
6820 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6821 		    "!Variable record length I/O\n");
6822 	} else {
6823 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6824 		    "!Fixed record length (%d byte blocks) I/O\n",
6825 		    un->un_dp->bsize);
6826 	}
6827 	ASSERT(mutex_owned(ST_MUTEX));
6828 	return (0);
6829 }
6830 
6831 static int
6832 st_determine_density(dev_t dev, int rw)
6833 {
6834 	int rval = 0;
6835 
6836 	GET_SOFT_STATE(dev);
6837 
6838 	ST_FUNC(ST_DEVINFO, st_determine_density);
6839 
6840 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6841 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6842 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6843 
6844 	ASSERT(mutex_owned(ST_MUTEX));
6845 
6846 	/*
6847 	 * If we're past BOT, density is determined already.
6848 	 */
6849 	if (un->un_pos.pmode == logical) {
6850 		if (un->un_pos.lgclblkno != 0) {
6851 			goto exit;
6852 		}
6853 	} else if (un->un_pos.pmode == legacy) {
6854 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
6855 			/*
6856 			 * XXX: put in a bitch message about attempting to
6857 			 * XXX: change density past BOT.
6858 			 */
6859 			goto exit;
6860 		}
6861 	} else {
6862 		goto exit;
6863 	}
6864 
6865 
6866 	/*
6867 	 * If we're going to be writing, we set the density
6868 	 */
6869 	if (rw == 0 || rw == B_WRITE) {
6870 		/* un_curdens is used as an index into densities table */
6871 		un->un_curdens = MT_DENSITY(un->un_dev);
6872 		if (st_set_density(dev)) {
6873 			rval = -1;
6874 		}
6875 		goto exit;
6876 	}
6877 
6878 	/*
6879 	 * If density is known already,
6880 	 * we don't have to get it again.(?)
6881 	 */
6882 	if (!un->un_density_known) {
6883 		if (st_get_density(dev)) {
6884 			rval = -1;
6885 		}
6886 	}
6887 
6888 exit:
6889 	ASSERT(mutex_owned(ST_MUTEX));
6890 	return (rval);
6891 }
6892 
6893 
6894 /*
6895  * Try to determine density. We do this by attempting to read the
6896  * first record off the tape, cycling through the available density
6897  * codes as we go.
6898  */
6899 
6900 static int
6901 st_get_density(dev_t dev)
6902 {
6903 	int succes = 0, rval = -1, i;
6904 	uint_t size;
6905 	uchar_t dens, olddens;
6906 
6907 	GET_SOFT_STATE(dev);
6908 
6909 	ST_FUNC(ST_DEVINFO, st_get_density);
6910 
6911 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6912 	    "st_get_density(dev = 0x%lx)\n", dev);
6913 
6914 	ASSERT(mutex_owned(ST_MUTEX));
6915 
6916 	/*
6917 	 * If Auto Density override is enabled The drive has
6918 	 * only one density and there is no point in attempting
6919 	 * find the correct one.
6920 	 *
6921 	 * Since most modern drives auto detect the density
6922 	 * and format of the recorded media before they come
6923 	 * ready. What this function does is a legacy behavior
6924 	 * and modern drives not only don't need it, The backup
6925 	 * utilities that do positioning via uscsi find the un-
6926 	 * expected rewinds problematic.
6927 	 *
6928 	 * The drives that need this are old reel to reel devices.
6929 	 * I took a swag and said they must be scsi-1 or older.
6930 	 * I don't beleave there will any of the newer devices
6931 	 * that need this. There will be some scsi-1 devices that
6932 	 * don't need this but I don't think they will be using the
6933 	 * BIG aftermarket backup and restore utilitys.
6934 	 */
6935 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6936 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6937 		un->un_density_known = 1;
6938 		rval = 0;
6939 		goto exit;
6940 	}
6941 
6942 	/*
6943 	 * This will only work on variable record length tapes
6944 	 * if and only if all variable record length tapes autodensity
6945 	 * select.
6946 	 */
6947 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6948 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6949 
6950 	/*
6951 	 * Start at the specified density
6952 	 */
6953 
6954 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6955 
6956 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6957 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
6958 		/*
6959 		 * If we've done this density before,
6960 		 * don't bother to do it again.
6961 		 */
6962 		dens = un->un_dp->densities[un->un_curdens];
6963 		if (i > 0 && dens == olddens)
6964 			continue;
6965 		olddens = dens;
6966 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6967 		    "trying density 0x%x\n", dens);
6968 		if (st_set_density(dev)) {
6969 			continue;
6970 		}
6971 
6972 		/*
6973 		 * XXX - the creates lots of headaches and slowdowns - must
6974 		 * fix.
6975 		 */
6976 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6977 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6978 			break;
6979 		}
6980 		if (succes) {
6981 			st_init(un);
6982 			rval = 0;
6983 			un->un_density_known = 1;
6984 			break;
6985 		}
6986 	}
6987 	kmem_free(un->un_tmpbuf, size);
6988 	un->un_tmpbuf = 0;
6989 
6990 exit:
6991 	ASSERT(mutex_owned(ST_MUTEX));
6992 	return (rval);
6993 }
6994 
6995 static int
6996 st_set_density(dev_t dev)
6997 {
6998 	int rval = 0;
6999 
7000 	GET_SOFT_STATE(dev);
7001 
7002 	ST_FUNC(ST_DEVINFO, st_set_density);
7003 
7004 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7005 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
7006 	    un->un_dp->densities[un->un_curdens]);
7007 
7008 	ASSERT(mutex_owned(ST_MUTEX));
7009 
7010 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7011 
7012 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7013 		/*
7014 		 * If auto density override is not set, Use mode select
7015 		 * to set density and compression.
7016 		 */
7017 		if (st_modeselect(un)) {
7018 			rval = -1;
7019 		}
7020 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7021 		/*
7022 		 * If auto density and mode select compression are set,
7023 		 * This is a drive with one density code but compression
7024 		 * can be enabled or disabled.
7025 		 * Set compression but no need to set density.
7026 		 */
7027 		rval = st_set_compression(un);
7028 		if ((rval != 0) && (rval != EALREADY)) {
7029 			rval = -1;
7030 		} else {
7031 			rval = 0;
7032 		}
7033 	}
7034 
7035 	/* If sucessful set density and/or compression, mark density known */
7036 	if (rval == 0) {
7037 		un->un_density_known = 1;
7038 	}
7039 
7040 	ASSERT(mutex_owned(ST_MUTEX));
7041 	return (rval);
7042 }
7043 
7044 static int
7045 st_loadtape(dev_t dev)
7046 {
7047 	int rval;
7048 
7049 	GET_SOFT_STATE(dev);
7050 
7051 	ST_FUNC(ST_DEVINFO, st_load_tape);
7052 
7053 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7054 	    "st_loadtape(dev = 0x%lx)\n", dev);
7055 
7056 	ASSERT(mutex_owned(ST_MUTEX));
7057 
7058 	/*
7059 	 * 'LOAD' the tape to BOT by rewinding
7060 	 */
7061 	rval = st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD);
7062 	if (rval == 0) {
7063 		st_init(un);
7064 		un->un_density_known = 0;
7065 	}
7066 
7067 	ASSERT(mutex_owned(ST_MUTEX));
7068 	return (rval);
7069 }
7070 
7071 
7072 /*
7073  * Note: QIC devices aren't so smart.  If you try to append
7074  * after EOM, the write can fail because the device doesn't know
7075  * it's at EOM.	 In that case, issue a read.  The read should fail
7076  * because there's no data, but the device knows it's at EOM,
7077  * so a subsequent write should succeed.  To further confuse matters,
7078  * the target returns the same error if the tape is positioned
7079  * such that a write would overwrite existing data.  That's why
7080  * we have to do the append test.  A read in the middle of
7081  * recorded data would succeed, thus indicating we're attempting
7082  * something illegal.
7083  */
7084 
7085 
7086 static void
7087 st_test_append(struct buf *bp)
7088 {
7089 	dev_t dev = bp->b_edev;
7090 	struct scsi_tape *un;
7091 	uchar_t status;
7092 	unsigned bcount;
7093 
7094 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7095 
7096 	ST_FUNC(ST_DEVINFO, st_test_append);
7097 
7098 	ASSERT(mutex_owned(ST_MUTEX));
7099 
7100 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7101 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7102 
7103 	un->un_laststate = un->un_state;
7104 	un->un_state = ST_STATE_APPEND_TESTING;
7105 	un->un_test_append = 0;
7106 
7107 	/*
7108 	 * first, map in the buffer, because we're doing a double write --
7109 	 * first into the kernel, then onto the tape.
7110 	 */
7111 	bp_mapin(bp);
7112 
7113 	/*
7114 	 * get a copy of the data....
7115 	 */
7116 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7117 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7118 
7119 	/*
7120 	 * attempt the write..
7121 	 */
7122 
7123 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7124 success:
7125 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7126 		    "append write succeeded\n");
7127 		bp->b_resid = un->un_sbufp->b_resid;
7128 		mutex_exit(ST_MUTEX);
7129 		bcount = (unsigned)bp->b_bcount;
7130 		biodone(bp);
7131 		mutex_enter(ST_MUTEX);
7132 		un->un_laststate = un->un_state;
7133 		un->un_state = ST_STATE_OPEN;
7134 		kmem_free(un->un_tmpbuf, bcount);
7135 		un->un_tmpbuf = NULL;
7136 		return;
7137 	}
7138 
7139 	/*
7140 	 * The append failed. Do a short read. If that fails,  we are at EOM
7141 	 * so we can retry the write command. If that succeeds, than we're
7142 	 * all screwed up (the controller reported a real error).
7143 	 *
7144 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7145 	 * XXX: block size?
7146 	 *
7147 	 */
7148 	status = un->un_status;
7149 	un->un_status = 0;
7150 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
7151 	if (un->un_status == KEY_BLANK_CHECK) {
7152 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7153 		    "append at EOM\n");
7154 		/*
7155 		 * Okay- the read failed. We should actually have confused
7156 		 * the controller enough to allow writing. In any case, the
7157 		 * i/o is on its own from here on out.
7158 		 */
7159 		un->un_laststate = un->un_state;
7160 		un->un_state = ST_STATE_OPEN;
7161 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7162 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
7163 		    SYNC_CMD) == 0) {
7164 			goto success;
7165 		}
7166 	}
7167 
7168 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7169 	    "append write failed- not at EOM\n");
7170 	bp->b_resid = bp->b_bcount;
7171 	st_bioerror(bp, EIO);
7172 
7173 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7174 	    "st_test_append : EIO : append write failed - not at EOM");
7175 
7176 	/*
7177 	 * backspace one record to get back to where we were
7178 	 */
7179 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7180 		un->un_pos.pmode = invalid;
7181 	}
7182 
7183 	un->un_err_resid = bp->b_resid;
7184 	un->un_status = status;
7185 
7186 	/*
7187 	 * Note: biodone will do a bp_mapout()
7188 	 */
7189 	mutex_exit(ST_MUTEX);
7190 	bcount = (unsigned)bp->b_bcount;
7191 	biodone(bp);
7192 	mutex_enter(ST_MUTEX);
7193 	un->un_laststate = un->un_state;
7194 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7195 	kmem_free(un->un_tmpbuf, bcount);
7196 	un->un_tmpbuf = NULL;
7197 }
7198 
7199 /*
7200  * Special command handler
7201  */
7202 
7203 /*
7204  * common st_cmd code. The fourth parameter states
7205  * whether the caller wishes to await the results
7206  * Note the release of the mutex during most of the function
7207  */
7208 static int
7209 st_cmd(dev_t dev, int com, int count, int wait)
7210 {
7211 	struct buf *bp;
7212 	int err;
7213 
7214 	GET_SOFT_STATE(dev);
7215 
7216 	ST_FUNC(ST_DEVINFO, st_cmd);
7217 
7218 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7219 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
7220 	    dev, com, count, wait);
7221 
7222 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7223 	ASSERT(mutex_owned(ST_MUTEX));
7224 
7225 #ifdef STDEBUG
7226 	if ((st_debug & 0xf)) {
7227 		st_debug_cmds(un, com, count, wait);
7228 	}
7229 #endif
7230 
7231 	/* check to see if this command requires the drive to be reserved */
7232 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7233 
7234 	if (err) {
7235 		return (err);
7236 	}
7237 
7238 	while (un->un_sbuf_busy)
7239 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7240 	un->un_sbuf_busy = 1;
7241 
7242 	bp = un->un_sbufp;
7243 	bzero(bp, sizeof (buf_t));
7244 
7245 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7246 
7247 	/*
7248 	 * Set count to the actual size of the data tranfer.
7249 	 * For commands with no data transfer, set bp->b_bcount
7250 	 * to the value to be used when constructing the
7251 	 * cdb in st_make_cmd().
7252 	 */
7253 	switch (com) {
7254 	case SCMD_READ:
7255 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7256 		    "special read %d\n", count);
7257 		bp->b_flags |= B_READ;
7258 		bp->b_un.b_addr = un->un_tmpbuf;
7259 		break;
7260 
7261 	case SCMD_WRITE:
7262 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7263 		    "special write %d\n", count);
7264 		bp->b_un.b_addr = un->un_tmpbuf;
7265 		break;
7266 
7267 	case SCMD_WRITE_FILE_MARK:
7268 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7269 		    "write %d file marks\n", count);
7270 		bp->b_bcount = count;
7271 		count = 0;
7272 		break;
7273 
7274 	case SCMD_REWIND:
7275 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7276 		bp->b_bcount = 0;
7277 		count = 0;
7278 		break;
7279 
7280 	case SCMD_SPACE:
7281 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7282 		/*
7283 		 * XXX The user could have entered a number that will
7284 		 * not fit in the 12 bit count field. Whats new here
7285 		 * checking that. Down the road this should use space(16).
7286 		 */
7287 		if ((SPACE_CNT(count) > 0x7fffff) ||
7288 		    (SPACE_CNT(count) < -(0x7fffff))) {
7289 			un->un_sbuf_busy = 0;
7290 			cv_signal(&un->un_sbuf_cv);
7291 			return (EINVAL);
7292 		}
7293 		bp->b_bcount = count;
7294 		count = 0;
7295 		break;
7296 
7297 	case SCMD_RESERVE:
7298 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7299 		bp->b_bcount = 0;
7300 		count = 0;
7301 		break;
7302 
7303 	case SCMD_RELEASE:
7304 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7305 		bp->b_bcount = 0;
7306 		count = 0;
7307 		break;
7308 
7309 	case SCMD_LOAD:
7310 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7311 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7312 		bp->b_bcount = count;
7313 		count = 0;
7314 		break;
7315 
7316 	case SCMD_ERASE:
7317 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7318 		    "erase tape\n");
7319 		bp->b_bcount = 0;
7320 		count = 0;
7321 		break;
7322 
7323 	case SCMD_MODE_SENSE:
7324 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7325 		    "mode sense\n");
7326 		bp->b_flags |= B_READ;
7327 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7328 		break;
7329 
7330 	case SCMD_MODE_SELECT:
7331 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7332 		    "mode select\n");
7333 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7334 		break;
7335 
7336 	case SCMD_READ_BLKLIM:
7337 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7338 		    "read block limits\n");
7339 		bp->b_flags |= B_READ;
7340 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7341 		break;
7342 
7343 	case SCMD_TEST_UNIT_READY:
7344 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7345 		    "test unit ready\n");
7346 		bp->b_bcount = 0;
7347 		count = 0;
7348 		break;
7349 
7350 	case SCMD_DOORLOCK:
7351 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7352 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7353 		bp->b_bcount = count = 0;
7354 		break;
7355 
7356 	case SCMD_READ_POSITION:
7357 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7358 		    "read position\n");
7359 		switch (un->un_read_pos_type) {
7360 		case LONG_POS:
7361 			count = sizeof (tape_position_long_t);
7362 			break;
7363 		case EXT_POS:
7364 			count = min(count, sizeof (tape_position_ext_t));
7365 			break;
7366 		case SHORT_POS:
7367 			count = sizeof (tape_position_t);
7368 			break;
7369 		default:
7370 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7371 			    "Unknown read position type 0x%x in "
7372 			    "st_make_cmd()\n", un->un_read_pos_type);
7373 		}
7374 		bp->b_bcount = count;
7375 		bp->b_flags |= B_READ;
7376 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7377 		break;
7378 
7379 	default:
7380 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7381 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
7382 	}
7383 
7384 	mutex_exit(ST_MUTEX);
7385 
7386 	if (count > 0) {
7387 		/*
7388 		 * We're going to do actual I/O.
7389 		 * Set things up for physio.
7390 		 */
7391 		struct iovec aiov;
7392 		struct uio auio;
7393 		struct uio *uio = &auio;
7394 
7395 		bzero(&auio, sizeof (struct uio));
7396 		bzero(&aiov, sizeof (struct iovec));
7397 		aiov.iov_base = bp->b_un.b_addr;
7398 		aiov.iov_len = count;
7399 
7400 		uio->uio_iov = &aiov;
7401 		uio->uio_iovcnt = 1;
7402 		uio->uio_resid = aiov.iov_len;
7403 		uio->uio_segflg = UIO_SYSSPACE;
7404 
7405 		/*
7406 		 * Let physio do the rest...
7407 		 */
7408 		bp->b_forw = (struct buf *)(uintptr_t)com;
7409 		bp->b_back = NULL;
7410 		err = physio(st_strategy, bp, dev,
7411 		    (bp->b_flags & B_READ) ? B_READ : B_WRITE,
7412 		    st_minphys, uio);
7413 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7414 		    "st_cmd: physio returns %d\n", err);
7415 	} else {
7416 		/*
7417 		 * Mimic physio
7418 		 */
7419 		bp->b_forw = (struct buf *)(uintptr_t)com;
7420 		bp->b_back = NULL;
7421 		bp->b_edev = dev;
7422 		bp->b_dev = cmpdev(dev);
7423 		bp->b_blkno = 0;
7424 		bp->b_resid = 0;
7425 		(void) st_strategy(bp);
7426 		if (!wait) {
7427 			/*
7428 			 * This is an async command- the caller won't wait
7429 			 * and doesn't care about errors.
7430 			 */
7431 			mutex_enter(ST_MUTEX);
7432 			return (0);
7433 		}
7434 
7435 		/*
7436 		 * BugTraq #4260046
7437 		 * ----------------
7438 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7439 		 * unconditionally. The old comment said...
7440 		 *
7441 		 * "if strategy was flagged with  persistent errors, we would
7442 		 *  have an error here, and the bp would never be sent, so we
7443 		 *  don't want to wait on a bp that was never sent...or hang"
7444 		 *
7445 		 * The new rationale, courtesy of Chitrank...
7446 		 *
7447 		 * "we should unconditionally biowait() here because
7448 		 *  st_strategy() will do a biodone() in the persistent error
7449 		 *  case and the following biowait() will return immediately.
7450 		 *  If not, in the case of "errors after pkt alloc" in
7451 		 *  st_start(), we will not biowait here which will cause the
7452 		 *  next biowait() to return immediately which will cause
7453 		 *  us to send out the next command. In the case where both of
7454 		 *  these use the sbuf, when the first command completes we'll
7455 		 *  free the packet attached to sbuf and the same pkt will
7456 		 *  get freed again when we complete the second command.
7457 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7458 		 *  st_start() for the pkt alloc failure case because physio()
7459 		 *  does biowait() and will hang if we don't do biodone()"
7460 		 */
7461 
7462 		err = biowait(bp);
7463 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7464 		    "st_cmd: biowait returns %d\n", err);
7465 	}
7466 	mutex_enter(ST_MUTEX);
7467 
7468 	un->un_sbuf_busy = 0;
7469 
7470 	/*
7471 	 * If was a space command need to update logical block position.
7472 	 * If the command failed such that positioning is invalid, Don't
7473 	 * update the position as the user must do this to validate the
7474 	 * position for data protection.
7475 	 */
7476 	if ((com == SCMD_SPACE) && (un->un_pos.pmode != invalid)) {
7477 		uchar_t status = un->un_status;
7478 		(void) st_update_block_pos(un);
7479 		un->un_status = status;
7480 	}
7481 
7482 	cv_signal(&un->un_sbuf_cv);
7483 	return (err);
7484 }
7485 
7486 static int
7487 st_set_compression(struct scsi_tape *un)
7488 {
7489 	int rval;
7490 	int turn_compression_on;
7491 	minor_t minor;
7492 
7493 	ST_FUNC(ST_DEVINFO, st_set_compression);
7494 
7495 	/*
7496 	 * Drive either dosn't have compression or it is controlled with
7497 	 * special density codes. Return ENOTTY so caller
7498 	 * knows nothing was done.
7499 	 */
7500 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7501 		un->un_comp_page = 0;
7502 		return (ENOTTY);
7503 	}
7504 
7505 	/* set compression based on minor node opened */
7506 	minor = MT_DENSITY(un->un_dev);
7507 
7508 	/*
7509 	 * If this the compression density or
7510 	 * the drive has two densities and uses mode select for
7511 	 * control of compression turn on compression for MT_DENSITY2
7512 	 * as well.
7513 	 */
7514 	if ((minor == ST_COMPRESSION_DENSITY) ||
7515 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7516 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7517 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7518 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7519 
7520 		turn_compression_on = 1;
7521 	} else {
7522 		turn_compression_on = 0;
7523 	}
7524 
7525 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7526 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7527 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7528 
7529 	/*
7530 	 * Need to determine which page does the device use for compression.
7531 	 * First try the data compression page. If this fails try the device
7532 	 * configuration page
7533 	 */
7534 
7535 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7536 		rval = st_set_datacomp_page(un, turn_compression_on);
7537 		if (rval == EALREADY) {
7538 			return (rval);
7539 		}
7540 		if (rval != 0) {
7541 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7542 				/*
7543 				 * This device does not support data
7544 				 * compression page
7545 				 */
7546 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7547 			} else if (un->un_state >= ST_STATE_OPEN) {
7548 				un->un_pos.pmode = invalid;
7549 				rval = EIO;
7550 			} else {
7551 				rval = -1;
7552 			}
7553 		} else {
7554 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7555 		}
7556 	}
7557 
7558 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7559 		rval = st_set_devconfig_page(un, turn_compression_on);
7560 		if (rval == EALREADY) {
7561 			return (rval);
7562 		}
7563 		if (rval != 0) {
7564 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7565 				/*
7566 				 * This device does not support
7567 				 * compression at all advice the
7568 				 * user and unset ST_MODE_SEL_COMP
7569 				 */
7570 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7571 				un->un_comp_page = 0;
7572 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7573 				    "Device Does Not Support Compression\n");
7574 			} else if (un->un_state >= ST_STATE_OPEN) {
7575 				un->un_pos.pmode = invalid;
7576 				rval = EIO;
7577 			} else {
7578 				rval = -1;
7579 			}
7580 		}
7581 	}
7582 
7583 	return (rval);
7584 }
7585 
7586 /*
7587  * set or unset compression thru device configuration page.
7588  */
7589 static int
7590 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7591 {
7592 	unsigned char cflag;
7593 	int rval = 0;
7594 
7595 
7596 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7597 
7598 	ASSERT(mutex_owned(ST_MUTEX));
7599 	/*
7600 	 * Figure what to set compression flag to.
7601 	 */
7602 	if (compression_on) {
7603 		/* They have selected a compression node */
7604 		if (un->un_dp->type == ST_TYPE_FUJI) {
7605 			cflag = 0x84;   /* use EDRC */
7606 		} else {
7607 			cflag = ST_DEV_CONFIG_DEF_COMP;
7608 		}
7609 	} else {
7610 		cflag = ST_DEV_CONFIG_NO_COMP;
7611 	}
7612 
7613 	/*
7614 	 * If compression is already set the way it was requested.
7615 	 * And if this not the first time we has tried.
7616 	 */
7617 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7618 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7619 		return (EALREADY);
7620 	}
7621 
7622 	un->un_mspl->page.dev.comp_alg = cflag;
7623 	/*
7624 	 * need to send mode select even if correct compression is
7625 	 * already set since need to set density code
7626 	 */
7627 
7628 #ifdef STDEBUG
7629 	if ((st_debug & 0xf) >= 6) {
7630 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7631 		    "st_set_devconfig_page: sense data for mode select",
7632 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7633 	}
7634 #endif
7635 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7636 
7637 	return (rval);
7638 }
7639 
7640 /*
7641  * set/reset compression bit thru data compression page
7642  */
7643 static int
7644 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7645 {
7646 	int compression_on_already;
7647 	int rval = 0;
7648 
7649 
7650 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7651 
7652 	ASSERT(mutex_owned(ST_MUTEX));
7653 	/*
7654 	 * If drive is not capable of compression (at this time)
7655 	 * return EALREADY so caller doesn't think that this page
7656 	 * is not supported. This check is for drives that can
7657 	 * disable compression from the front panel or configuration.
7658 	 * I doubt that a drive that supports this page is not really
7659 	 * capable of compression.
7660 	 */
7661 	if (un->un_mspl->page.comp.dcc == 0) {
7662 		return (EALREADY);
7663 	}
7664 
7665 	/* See if compression currently turned on */
7666 	if (un->un_mspl->page.comp.dce) {
7667 		compression_on_already = 1;
7668 	} else {
7669 		compression_on_already = 0;
7670 	}
7671 
7672 	/*
7673 	 * If compression is already set the way it was requested.
7674 	 * And if this not the first time we has tried.
7675 	 */
7676 	if ((compression_on == compression_on_already) &&
7677 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7678 		return (EALREADY);
7679 	}
7680 
7681 	/*
7682 	 * if we are already set to the appropriate compression
7683 	 * mode, don't set it again
7684 	 */
7685 	if (compression_on) {
7686 		/* compression selected */
7687 		un->un_mspl->page.comp.dce = 1;
7688 	} else {
7689 		un->un_mspl->page.comp.dce = 0;
7690 	}
7691 
7692 
7693 #ifdef STDEBUG
7694 	if ((st_debug & 0xf) >= 6) {
7695 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7696 		    "st_set_datacomp_page: sense data for mode select",
7697 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7698 	}
7699 #endif
7700 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7701 
7702 	return (rval);
7703 }
7704 
7705 static int
7706 st_modesense(struct scsi_tape *un)
7707 {
7708 	int rval;
7709 	uchar_t page;
7710 
7711 	ST_FUNC(ST_DEVINFO, st_modesense);
7712 
7713 	page = un->un_comp_page;
7714 
7715 	switch (page) {
7716 	case ST_DEV_DATACOMP_PAGE:
7717 	case ST_DEV_CONFIG_PAGE: /* fall through */
7718 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7719 		    sizeof (struct seq_mode));
7720 		break;
7721 
7722 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7723 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7724 			page = ST_DEV_DATACOMP_PAGE;
7725 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7726 			    sizeof (struct seq_mode));
7727 			if (rval == 0 && un->un_mspl->page_code == page) {
7728 				un->un_comp_page = page;
7729 				break;
7730 			}
7731 			page = ST_DEV_CONFIG_PAGE;
7732 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7733 			    sizeof (struct seq_mode));
7734 			if (rval == 0 && un->un_mspl->page_code == page) {
7735 				un->un_comp_page = page;
7736 				break;
7737 			}
7738 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7739 			un->un_comp_page = 0;
7740 		} else {
7741 			un->un_comp_page = 0;
7742 		}
7743 
7744 	default:	/* fall through */
7745 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7746 	}
7747 	return (rval);
7748 }
7749 
7750 static int
7751 st_modeselect(struct scsi_tape *un)
7752 {
7753 	int rval = 0;
7754 	int ix;
7755 
7756 	ST_FUNC(ST_DEVINFO, st_modeselect);
7757 
7758 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7759 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7760 	    un->un_dev, un->un_mspl->density);
7761 
7762 	ASSERT(mutex_owned(ST_MUTEX));
7763 
7764 	/*
7765 	 * The parameter list should be the same for all of the
7766 	 * cases that follow so set them here
7767 	 *
7768 	 * Try mode select first if if fails set fields manually
7769 	 */
7770 	rval = st_modesense(un);
7771 	if (rval != 0) {
7772 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7773 		    "st_modeselect: First mode sense failed\n");
7774 		un->un_mspl->bd_len  = 8;
7775 		un->un_mspl->high_nb = 0;
7776 		un->un_mspl->mid_nb  = 0;
7777 		un->un_mspl->low_nb  = 0;
7778 	}
7779 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7780 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7781 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7782 
7783 
7784 	/*
7785 	 * If configured to use a specific density code for a media type.
7786 	 * curdens is previously set by the minor node opened.
7787 	 * If the media type doesn't match the minor node we change it so it
7788 	 * looks like the correct one was opened.
7789 	 */
7790 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7791 		uchar_t best;
7792 
7793 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7794 			if (un->un_mspl->media_type ==
7795 			    un->un_dp->mediatype[ix]) {
7796 				best = ix;
7797 				/*
7798 				 * It matches but it might not be the only one.
7799 				 * Use the highest matching media type but not
7800 				 * to exceed the density selected by the open.
7801 				 */
7802 				if (ix < un->un_curdens) {
7803 					continue;
7804 				}
7805 				un->un_curdens = ix;
7806 				break;
7807 			}
7808 		}
7809 		/* If a match was found best will not be 0xff any more */
7810 		if (best < NDENSITIES) {
7811 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7812 			    "found media 0x%X using density 0x%X\n",
7813 			    un->un_mspl->media_type,
7814 			    un->un_dp->densities[best]);
7815 			un->un_mspl->density = un->un_dp->densities[best];
7816 		} else {
7817 			/* Otherwise set density based on minor node opened */
7818 			un->un_mspl->density =
7819 			    un->un_dp->densities[un->un_curdens];
7820 		}
7821 	} else {
7822 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7823 	}
7824 
7825 	if (un->un_dp->options & ST_NOBUF) {
7826 		un->un_mspl->bufm = 0;
7827 	} else {
7828 		un->un_mspl->bufm = 1;
7829 	}
7830 
7831 	rval = st_set_compression(un);
7832 
7833 	/*
7834 	 * If st_set_compression returned invalid or already it
7835 	 * found no need to do the mode select.
7836 	 * So do it here.
7837 	 */
7838 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7839 
7840 		/* Zero non-writeable fields */
7841 		un->un_mspl->data_len = 0;
7842 		un->un_mspl->media_type = 0;
7843 		un->un_mspl->wp = 0;
7844 
7845 		/* need to set the density code */
7846 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7847 		if (rval != 0) {
7848 			if (un->un_state >= ST_STATE_OPEN) {
7849 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7850 				    "unable to set tape mode\n");
7851 				un->un_pos.pmode = invalid;
7852 				rval = EIO;
7853 			} else {
7854 				rval = -1;
7855 			}
7856 		}
7857 	}
7858 
7859 	/*
7860 	 * The spec recommends to send a mode sense after a mode select
7861 	 */
7862 	(void) st_modesense(un);
7863 
7864 	ASSERT(mutex_owned(ST_MUTEX));
7865 
7866 	return (rval);
7867 }
7868 
7869 /*
7870  * st_gen_mode_sense
7871  *
7872  * generic mode sense.. it allows for any page
7873  */
7874 static int
7875 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7876     int page_size)
7877 {
7878 
7879 	int r;
7880 	char	cdb[CDB_GROUP0];
7881 	struct uscsi_cmd *com;
7882 
7883 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
7884 
7885 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7886 
7887 	bzero(cdb, CDB_GROUP0);
7888 	cdb[0] = SCMD_MODE_SENSE;
7889 	cdb[2] = (char)page;
7890 	cdb[4] = (char)page_size;
7891 
7892 	com->uscsi_cdb = cdb;
7893 	com->uscsi_cdblen = CDB_GROUP0;
7894 	com->uscsi_bufaddr = (caddr_t)page_data;
7895 	com->uscsi_buflen = page_size;
7896 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7897 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7898 
7899 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7900 	kmem_free(com, sizeof (*com));
7901 	return (r);
7902 }
7903 
7904 /*
7905  * st_gen_mode_select
7906  *
7907  * generic mode select.. it allows for any page
7908  */
7909 static int
7910 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7911     int page_size)
7912 {
7913 
7914 	int r;
7915 	char cdb[CDB_GROUP0];
7916 	struct uscsi_cmd *com;
7917 
7918 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
7919 
7920 	/* Zero non-writeable fields */
7921 	page_data->data_len = 0;
7922 	page_data->media_type = 0;
7923 	page_data->wp = 0;
7924 
7925 	/*
7926 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7927 	 */
7928 	if (page_size > MSIZE) {
7929 		page_data->ps = 0;
7930 	}
7931 
7932 
7933 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7934 
7935 	/*
7936 	 * then, do a mode select to set what ever info
7937 	 */
7938 	bzero(cdb, CDB_GROUP0);
7939 	cdb[0] = SCMD_MODE_SELECT;
7940 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7941 	cdb[4] = (char)page_size;
7942 
7943 	com->uscsi_cdb = cdb;
7944 	com->uscsi_cdblen = CDB_GROUP0;
7945 	com->uscsi_bufaddr = (caddr_t)page_data;
7946 	com->uscsi_buflen = page_size;
7947 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7948 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
7949 
7950 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7951 
7952 	kmem_free(com, sizeof (*com));
7953 	return (r);
7954 }
7955 
7956 static int
7957 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
7958 {
7959 	int rval;
7960 	char cdb[CDB_GROUP0];
7961 	struct uscsi_cmd *com;
7962 
7963 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
7964 
7965 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7966 
7967 	bzero(cdb, CDB_GROUP0);
7968 	cdb[0] = SCMD_READ_BLKLIM;
7969 
7970 	com->uscsi_cdb = cdb;
7971 	com->uscsi_cdblen = CDB_GROUP0;
7972 	com->uscsi_bufaddr = (caddr_t)read_blk;
7973 	com->uscsi_buflen = sizeof (struct read_blklim);
7974 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7975 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7976 
7977 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7978 	if (com->uscsi_status || com->uscsi_resid) {
7979 		rval = -1;
7980 	}
7981 
7982 	kmem_free(com, sizeof (*com));
7983 	return (rval);
7984 }
7985 
7986 static int
7987 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
7988     size_t buflen)
7989 {
7990 	int rval;
7991 	char cdb[CDB_GROUP1];
7992 	struct uscsi_cmd *com;
7993 
7994 	ST_FUNC(ST_DEVINFO, st_report_density_support);
7995 
7996 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7997 
7998 	bzero(cdb, CDB_GROUP1);
7999 	cdb[0] = SCMD_REPORT_DENSITIES;
8000 	cdb[7] = (buflen & 0xff00) >> 8;
8001 	cdb[8] = buflen & 0xff;
8002 
8003 	com->uscsi_cdb = cdb;
8004 	com->uscsi_cdblen = CDB_GROUP1;
8005 	com->uscsi_bufaddr = (caddr_t)density_data;
8006 	com->uscsi_buflen = buflen;
8007 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8008 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8009 
8010 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
8011 	if (com->uscsi_status || com->uscsi_resid) {
8012 		rval = -1;
8013 	}
8014 
8015 	kmem_free(com, sizeof (*com));
8016 	return (rval);
8017 }
8018 
8019 static int
8020 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8021     uchar_t option_code, ushort_t service_action)
8022 {
8023 	int rval;
8024 	char cdb[CDB_GROUP5];
8025 	struct uscsi_cmd *com;
8026 	uint32_t allo_length;
8027 
8028 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8029 
8030 	allo_length = sizeof (struct one_com_des) +
8031 	    sizeof (struct com_timeout_des);
8032 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8033 
8034 	bzero(cdb, CDB_GROUP5);
8035 	cdb[0] = (char)SCMD_REPORT_TARGET_PORT_GROUPS;
8036 	cdb[1] = 0x0c; /* service action */
8037 	if (service_action) {
8038 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8039 		cdb[4] = (service_action & 0xff00) >> 8;
8040 		cdb[5] = service_action & 0xff;
8041 	} else {
8042 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8043 		    0x80); /* RCTD */
8044 	}
8045 	cdb[3] = option_code;
8046 	cdb[6] = (allo_length & 0xff000000) >> 24;
8047 	cdb[7] = (allo_length & 0xff0000) >> 16;
8048 	cdb[8] = (allo_length & 0xff00) >> 8;
8049 	cdb[9] = allo_length & 0xff;
8050 
8051 	com->uscsi_cdb = cdb;
8052 	com->uscsi_cdblen = CDB_GROUP5;
8053 	com->uscsi_bufaddr = (caddr_t)oper_data;
8054 	com->uscsi_buflen = allo_length;
8055 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8056 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8057 
8058 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
8059 	if (com->uscsi_status) {
8060 		rval = -1;
8061 	}
8062 
8063 	kmem_free(com, sizeof (*com));
8064 	return (rval);
8065 }
8066 
8067 /*
8068  * Changes devices blocksize and bsize to requested blocksize nblksz.
8069  * Returns returned value from first failed call or zero on success.
8070  */
8071 static int
8072 st_change_block_size(dev_t dev, uint32_t nblksz)
8073 {
8074 	struct seq_mode *current;
8075 	int rval;
8076 	uint32_t oldblksz;
8077 
8078 	GET_SOFT_STATE(dev);
8079 
8080 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8081 
8082 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8083 
8084 	/* Read current settings */
8085 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
8086 	if (rval != 0) {
8087 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8088 		    "mode sense for change block size failed: rval = %d", rval);
8089 		goto finish;
8090 	}
8091 
8092 	/* Figure the current block size */
8093 	oldblksz =
8094 	    (current->high_bl << 16) |
8095 	    (current->mid_bl << 8) |
8096 	    (current->low_bl);
8097 
8098 	/* If current block size is the same as requested were done */
8099 	if (oldblksz == nblksz) {
8100 		un->un_bsize = nblksz;
8101 		rval = 0;
8102 		goto finish;
8103 	}
8104 
8105 	/* Change to requested block size */
8106 	current->high_bl = (uchar_t)(nblksz >> 16);
8107 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8108 	current->low_bl  = (uchar_t)(nblksz);
8109 
8110 	/* Attempt to change block size */
8111 	rval = st_gen_mode_select(un, current, MSIZE);
8112 	if (rval != 0) {
8113 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8114 		    "Set new block size failed: rval = %d", rval);
8115 		goto finish;
8116 	}
8117 
8118 	/* Read back and verify setting */
8119 	rval = st_modesense(un);
8120 	if (rval == 0) {
8121 		un->un_bsize =
8122 		    (un->un_mspl->high_bl << 16) |
8123 		    (un->un_mspl->mid_bl << 8) |
8124 		    (un->un_mspl->low_bl);
8125 
8126 		if (un->un_bsize != nblksz) {
8127 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8128 			    "Blocksize set does not equal requested blocksize"
8129 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8130 			rval = EIO;
8131 		}
8132 	}
8133 finish:
8134 	kmem_free(current, MSIZE);
8135 	return (rval);
8136 }
8137 
8138 
8139 static void
8140 st_init(struct scsi_tape *un)
8141 {
8142 	ST_FUNC(ST_DEVINFO, st_init);
8143 
8144 	ASSERT(mutex_owned(ST_MUTEX));
8145 
8146 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8147 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8148 	    un->un_dev);
8149 
8150 	un->un_pos.blkno = 0;
8151 	un->un_pos.fileno = 0;
8152 	un->un_lastop = ST_OP_NIL;
8153 	un->un_pos.eof = ST_NO_EOF;
8154 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8155 	if (st_error_level != SCSI_ERR_ALL) {
8156 		if (DEBUGGING) {
8157 			st_error_level = SCSI_ERR_ALL;
8158 		} else {
8159 			st_error_level = SCSI_ERR_RETRYABLE;
8160 		}
8161 	}
8162 }
8163 
8164 
8165 static void
8166 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8167 {
8168 	struct scsi_pkt *pkt;
8169 	struct uscsi_cmd *ucmd;
8170 	int count, tval = 0;
8171 	uint_t addr = 0;
8172 	int flags = 0;
8173 	int cdb_len = CDB_GROUP0; /* default */
8174 	uchar_t com;
8175 	char fixbit;
8176 
8177 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8178 
8179 	ASSERT(mutex_owned(ST_MUTEX));
8180 
8181 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8182 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8183 
8184 
8185 	/*
8186 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8187 	 * Length Indicator bits on read/write commands, for setting
8188 	 * the Long bit on erase commands, and for setting the Code
8189 	 * Field bits on space commands.
8190 	 * XXX why do we set lastop here?
8191 	 */
8192 
8193 	if (bp != un->un_sbufp) {		/* regular raw I/O */
8194 		int stat_size = (un->un_arq_enabled ?
8195 		    sizeof (struct scsi_arq_status) : 1);
8196 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8197 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
8198 		if (pkt == NULL) {
8199 			goto exit;
8200 		}
8201 		SET_BP_PKT(bp, pkt);
8202 		if (un->un_bsize == 0) {
8203 			count = bp->b_bcount;
8204 			fixbit = 0;
8205 		} else {
8206 			count = bp->b_bcount / un->un_bsize;
8207 			fixbit = 1;
8208 		}
8209 		if (bp->b_flags & B_READ) {
8210 			com = SCMD_READ;
8211 			un->un_lastop = ST_OP_READ;
8212 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8213 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8214 				fixbit = 2;
8215 			}
8216 		} else {
8217 			com = SCMD_WRITE;
8218 			un->un_lastop = ST_OP_WRITE;
8219 		}
8220 
8221 		tval = un->un_dp->io_timeout;
8222 
8223 		/*
8224 		 * For really large xfers, increase timeout
8225 		 */
8226 		if (bp->b_bcount > (10 * ONE_MEG))
8227 			tval *= bp->b_bcount/(10 * ONE_MEG);
8228 
8229 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8230 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8231 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8232 
8233 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8234 		/*
8235 		 * uscsi - build command, allocate scsi resources
8236 		 */
8237 		st_make_uscsi_cmd(un, ucmd, bp, func);
8238 		goto exit;
8239 
8240 	} else {				/* special I/O */
8241 		int stat_size = (un->un_arq_enabled ?
8242 		    sizeof (struct scsi_arq_status) : 1);
8243 		struct buf *allocbp = NULL;
8244 		com = (uchar_t)(uintptr_t)bp->b_forw;
8245 		count = bp->b_bcount;
8246 
8247 		switch (com) {
8248 		case SCMD_READ:
8249 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8250 			    "special read %d\n", count);
8251 			if (un->un_bsize == 0) {
8252 				fixbit = 2;	/* suppress SILI */
8253 			} else {
8254 				fixbit = 1;	/* Fixed Block Mode */
8255 				count /= un->un_bsize;
8256 			}
8257 			allocbp = bp;
8258 			un->un_lastop = ST_OP_READ;
8259 			tval = un->un_dp->io_timeout;
8260 			break;
8261 
8262 		case SCMD_WRITE:
8263 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8264 			    "special write %d\n", count);
8265 			if (un->un_bsize != 0) {
8266 				fixbit = 1;	/* Fixed Block Mode */
8267 				count /= un->un_bsize;
8268 			} else {
8269 				fixbit = 0;
8270 			}
8271 			allocbp = bp;
8272 			un->un_lastop = ST_OP_WRITE;
8273 			tval = un->un_dp->io_timeout;
8274 			break;
8275 
8276 		case SCMD_WRITE_FILE_MARK:
8277 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8278 			    "write %d file marks\n", count);
8279 			un->un_lastop = ST_OP_WEOF;
8280 			fixbit = 0;
8281 			tval = un->un_dp->io_timeout;
8282 			break;
8283 
8284 		case SCMD_REWIND:
8285 			if (bp->b_flags & B_ASYNC) {
8286 				fixbit = 1;
8287 			} else {
8288 				fixbit = 0;
8289 			}
8290 			count = 0;
8291 			un->un_lastop = ST_OP_CTL;
8292 			tval = un->un_dp->rewind_timeout;
8293 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8294 			    "rewind\n");
8295 			break;
8296 
8297 		case SCMD_SPACE:
8298 			fixbit = SPACE_TYPE(count);
8299 			count = (int)SPACE_CNT(count);
8300 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8301 			    "space %s %d from file %d blk %d\n",
8302 			    space_strs[fixbit & 7], count,
8303 			    un->un_pos.fileno, un->un_pos.blkno);
8304 			un->un_lastop = ST_OP_CTL;
8305 			tval = un->un_dp->space_timeout;
8306 			break;
8307 
8308 		case SCMD_LOAD:
8309 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8310 			    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
8311 			fixbit = 0;
8312 
8313 			/* Loading or Unloading */
8314 			if (count & LD_LOAD) {
8315 				tval = un->un_dp->load_timeout;
8316 			} else {
8317 				tval = un->un_dp->unload_timeout;
8318 			}
8319 			/* Is Retension requested */
8320 			if (count & LD_RETEN) {
8321 				tval += un->un_dp->rewind_timeout;
8322 			}
8323 			un->un_lastop = ST_OP_CTL;
8324 			break;
8325 
8326 		case SCMD_ERASE:
8327 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8328 			    "erase tape\n");
8329 			count = 0;
8330 			/*
8331 			 * We support long erase only
8332 			 */
8333 			fixbit = 1;
8334 			tval = un->un_dp->erase_timeout;
8335 			un->un_lastop = ST_OP_CTL;
8336 			break;
8337 
8338 		case SCMD_MODE_SENSE:
8339 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8340 			    "mode sense\n");
8341 			allocbp = bp;
8342 			fixbit = 0;
8343 			tval = un->un_dp->non_motion_timeout;
8344 			un->un_lastop = ST_OP_CTL;
8345 			break;
8346 
8347 		case SCMD_MODE_SELECT:
8348 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8349 			    "mode select\n");
8350 			allocbp = bp;
8351 			fixbit = 0;
8352 			tval = un->un_dp->non_motion_timeout;
8353 			un->un_lastop = ST_OP_CTL;
8354 			break;
8355 
8356 		case SCMD_RESERVE:
8357 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8358 			    "reserve\n");
8359 			fixbit = 0;
8360 			tval = un->un_dp->non_motion_timeout;
8361 			un->un_lastop = ST_OP_CTL;
8362 			break;
8363 
8364 		case SCMD_RELEASE:
8365 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8366 			    "release\n");
8367 			fixbit = 0;
8368 			tval = un->un_dp->non_motion_timeout;
8369 			un->un_lastop = ST_OP_CTL;
8370 			break;
8371 
8372 		case SCMD_READ_BLKLIM:
8373 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8374 			    "read block limits\n");
8375 			allocbp = bp;
8376 			fixbit = count = 0;
8377 			tval = un->un_dp->non_motion_timeout;
8378 			un->un_lastop = ST_OP_CTL;
8379 			break;
8380 
8381 		case SCMD_TEST_UNIT_READY:
8382 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8383 			    "test unit ready\n");
8384 			fixbit = 0;
8385 			tval = un->un_dp->non_motion_timeout;
8386 			un->un_lastop = ST_OP_CTL;
8387 			break;
8388 
8389 		case SCMD_DOORLOCK:
8390 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8391 			    "prevent/allow media removal\n");
8392 			fixbit = 0;
8393 			tval = un->un_dp->non_motion_timeout;
8394 			un->un_lastop = ST_OP_CTL;
8395 			break;
8396 
8397 		case SCMD_READ_POSITION:
8398 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8399 			    "read position\n");
8400 			fixbit = un->un_read_pos_type;
8401 			cdb_len = CDB_GROUP1;
8402 			tval = un->un_dp->non_motion_timeout;
8403 			allocbp = bp;
8404 			un->un_lastop = ST_OP_CTL;
8405 			switch (un->un_read_pos_type) {
8406 			case LONG_POS:
8407 				count = 0;
8408 				break;
8409 			case EXT_POS:
8410 				count = sizeof (tape_position_ext_t);
8411 				break;
8412 			case SHORT_POS:
8413 				count = 0;
8414 				break;
8415 			default:
8416 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8417 				    "Unknown read position type 0x%x in "
8418 				    " st_make_cmd()\n", un->un_read_pos_type);
8419 			}
8420 			break;
8421 
8422 		default:
8423 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8424 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8425 			    com);
8426 		}
8427 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8428 		    0, 0, func, (caddr_t)un);
8429 		if (pkt == NULL) {
8430 			goto exit;
8431 		}
8432 		if (allocbp) {
8433 			ASSERT(geterror(allocbp) == 0);
8434 		}
8435 
8436 	}
8437 
8438 
8439 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8440 	    com, addr, (uint_t)count, 0);
8441 	FILL_SCSI1_LUN(un->un_sd, pkt);
8442 	/*
8443 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8444 	 */
8445 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8446 	pkt->pkt_flags = flags;
8447 
8448 #ifdef STDEBUG
8449 	if ((st_debug & 0xf) >= 6) {
8450 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8451 		    "cmd cdb", (char *)pkt->pkt_cdbp, cdb_len);
8452 	}
8453 #endif
8454 
8455 	/*
8456 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8457 	 * device, set the Vendor Unique bit to
8458 	 * write Short File Mark.
8459 	 */
8460 	if (com == SCMD_WRITE_FILE_MARK &&
8461 	    un->un_dp->options & ST_SHORT_FILEMARKS) {
8462 		switch (un->un_dp->type) {
8463 		case ST_TYPE_EXB8500:
8464 		case ST_TYPE_EXABYTE:
8465 			/*
8466 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8467 			 * is set to to write Short File Mark
8468 			 */
8469 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
8470 			break;
8471 
8472 		default:
8473 			/*
8474 			 * Well, if ST_SHORT_FILEMARKS is set for other
8475 			 * tape drives, it is just ignored
8476 			 */
8477 			break;
8478 		}
8479 	}
8480 	ASSERT(tval);
8481 	pkt->pkt_time = tval;
8482 	pkt->pkt_comp = st_intr;
8483 	pkt->pkt_private = (opaque_t)bp;
8484 
8485 	SET_BP_PKT(bp, pkt);
8486 
8487 exit:
8488 	ASSERT(mutex_owned(ST_MUTEX));
8489 }
8490 
8491 
8492 /*
8493  * Build a command based on a uscsi command;
8494  */
8495 static void
8496 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8497     struct buf *bp, int (*func)(caddr_t))
8498 {
8499 	struct scsi_pkt *pkt;
8500 	caddr_t cdb;
8501 	int	cdblen;
8502 	int stat_size;
8503 
8504 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8505 
8506 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8507 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8508 
8509 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8510 		stat_size = (un->un_arq_enabled ?
8511 		    sizeof (struct scsi_arq_status) : 1);
8512 	} else {
8513 		stat_size = 1;
8514 	}
8515 
8516 	ASSERT(mutex_owned(ST_MUTEX));
8517 
8518 	cdb = ucmd->uscsi_cdb;
8519 	cdblen = ucmd->uscsi_cdblen;
8520 
8521 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8522 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8523 	    ucmd->uscsi_buflen, bp->b_bcount);
8524 	pkt = scsi_init_pkt(ROUTE, NULL,
8525 	    (bp->b_bcount > 0) ? bp : NULL,
8526 	    cdblen, stat_size, 0, 0, func, (caddr_t)un);
8527 	if (pkt == NULL) {
8528 		goto exit;
8529 	}
8530 
8531 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8532 
8533 #ifdef STDEBUG
8534 	if ((st_debug & 0xf) >= 6) {
8535 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8536 		    "pkt_cdbp", (char *)cdb, cdblen);
8537 	}
8538 #endif
8539 
8540 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8541 		pkt->pkt_flags |= FLAG_SILENT;
8542 	}
8543 
8544 	pkt->pkt_time = ucmd->uscsi_timeout;
8545 	pkt->pkt_comp = st_intr;
8546 	pkt->pkt_private = (opaque_t)bp;
8547 
8548 	SET_BP_PKT(bp, pkt);
8549 exit:
8550 	ASSERT(mutex_owned(ST_MUTEX));
8551 }
8552 
8553 
8554 /*
8555  * restart cmd currently at the head of the runq
8556  *
8557  * If scsi_transport() succeeds or the retries
8558  * count exhausted, restore the throttle that was
8559  * zeroed out in st_handle_intr_busy().
8560  *
8561  */
8562 static void
8563 st_intr_restart(void *arg)
8564 {
8565 	struct scsi_tape *un = arg;
8566 	struct buf *bp;
8567 	int status = TRAN_ACCEPT;
8568 
8569 	mutex_enter(ST_MUTEX);
8570 
8571 	ST_FUNC(ST_DEVINFO, st_intr_restart);
8572 
8573 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8574 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
8575 
8576 	un->un_hib_tid = 0;
8577 
8578 	/*
8579 	 * move from waitq to runq, if there is anything on the waitq
8580 	 */
8581 	if ((bp = un->un_quef) == NULL) {
8582 		mutex_exit(ST_MUTEX);
8583 		return;
8584 	}
8585 
8586 	/*
8587 	 * Here we know :
8588 	 *	throttle = 0, via st_handle_intr_busy
8589 	 */
8590 
8591 	if (un->un_quel == bp) {
8592 		un->un_quel = NULL;
8593 		un->un_quef = NULL;	/* we know it's the first one */
8594 	} else {
8595 		un->un_quef = bp->b_actf;
8596 	}
8597 	bp->b_actf = NULL;
8598 
8599 	if (un->un_runqf) {
8600 		/*
8601 		 * not good, we don't want to requeue something after
8602 		 * another.
8603 		 */
8604 		mutex_exit(ST_MUTEX);
8605 		goto done_error;
8606 	} else {
8607 		un->un_runqf = bp;
8608 		un->un_runql = bp;
8609 	}
8610 
8611 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8612 
8613 	mutex_exit(ST_MUTEX);
8614 
8615 	status = scsi_transport(BP_PKT(bp));
8616 
8617 	mutex_enter(ST_MUTEX);
8618 
8619 	if (status != TRAN_ACCEPT) {
8620 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8621 		mutex_exit(ST_MUTEX);
8622 
8623 		if (status == TRAN_BUSY) {
8624 			if (st_handle_intr_busy(un, bp,
8625 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8626 				return;	/* timeout is setup again */
8627 		}
8628 
8629 	} else {
8630 		un->un_tran_retry_ct = 0;
8631 		if (un->un_last_throttle) {
8632 			un->un_throttle = un->un_last_throttle;
8633 		}
8634 		mutex_exit(ST_MUTEX);
8635 		return;
8636 	}
8637 
8638 done_error:
8639 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8640 	    "restart transport rejected\n");
8641 	bp->b_resid = bp->b_bcount;
8642 
8643 #ifndef __lock_lint
8644 	/*
8645 	 * warlock doesn't understand this potential
8646 	 * recursion?
8647 	 */
8648 	mutex_enter(ST_MUTEX);
8649 	if (un->un_last_throttle) {
8650 		un->un_throttle = un->un_last_throttle;
8651 	}
8652 	if (status != TRAN_ACCEPT)
8653 		ST_DO_ERRSTATS(un, st_transerrs);
8654 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8655 	SET_PE_FLAG(un);
8656 	st_bioerror(bp, EIO);
8657 	st_done_and_mutex_exit(un, bp);
8658 #endif
8659 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8660 	    "busy restart aborted\n");
8661 }
8662 
8663 /*
8664  * st_check_media():
8665  * Periodically check the media state using scsi_watch service;
8666  * this service calls back after TUR and possibly request sense
8667  * the callback handler (st_media_watch_cb()) decodes the request sense
8668  * data (if any)
8669  */
8670 
8671 static int
8672 st_check_media(dev_t dev, enum mtio_state state)
8673 {
8674 	int rval = 0;
8675 	enum mtio_state	prev_state;
8676 	opaque_t token = NULL;
8677 
8678 	GET_SOFT_STATE(dev);
8679 
8680 	ST_FUNC(ST_DEVINFO, st_check_media);
8681 
8682 	mutex_enter(ST_MUTEX);
8683 
8684 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8685 	    "st_check_media:state=%x, mediastate=%x\n",
8686 	    state, un->un_mediastate);
8687 
8688 	prev_state = un->un_mediastate;
8689 
8690 	/*
8691 	 * is there anything to do?
8692 	 */
8693 retry:
8694 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8695 		/*
8696 		 * submit the request to the scsi_watch service;
8697 		 * scsi_media_watch_cb() does the real work
8698 		 */
8699 		mutex_exit(ST_MUTEX);
8700 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8701 		    st_check_media_time, SENSE_LENGTH,
8702 		    st_media_watch_cb, (caddr_t)dev);
8703 		if (token == NULL) {
8704 			rval = EAGAIN;
8705 			goto done;
8706 		}
8707 		mutex_enter(ST_MUTEX);
8708 
8709 		un->un_swr_token = token;
8710 		un->un_specified_mediastate = state;
8711 
8712 		/*
8713 		 * now wait for media change
8714 		 * we will not be signalled unless mediastate == state but it
8715 		 * still better to test for this condition, since there
8716 		 * is a 5 sec cv_broadcast delay when
8717 		 *  mediastate == MTIO_INSERTED
8718 		 */
8719 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8720 		    "st_check_media:waiting for media state change\n");
8721 		while (un->un_mediastate == state) {
8722 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8723 				mutex_exit(ST_MUTEX);
8724 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8725 				    "st_check_media:waiting for media state "
8726 				    "was interrupted\n");
8727 				rval = EINTR;
8728 				goto done;
8729 			}
8730 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8731 			    "st_check_media:received signal, state=%x\n",
8732 			    un->un_mediastate);
8733 		}
8734 	}
8735 
8736 	/*
8737 	 * if we transitioned to MTIO_INSERTED, media has really been
8738 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8739 	 * Reset and retry the state change.  If everything is ok, replay
8740 	 * the open() logic.
8741 	 */
8742 	if ((un->un_mediastate == MTIO_INSERTED) &&
8743 	    (un->un_state == ST_STATE_OFFLINE)) {
8744 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8745 		    "st_check_media: calling st_cmd to confirm inserted\n");
8746 
8747 		/*
8748 		 * set this early so that TUR will make it through strategy
8749 		 * without triggering a st_tape_init().  We needed it set
8750 		 * before calling st_tape_init() ourselves anyway.  If TUR
8751 		 * fails, set it back
8752 		 */
8753 		un->un_state = ST_STATE_INITIALIZING;
8754 
8755 		/*
8756 		 * If not reserved fail as getting reservation conflict
8757 		 * will make this hang forever.
8758 		 */
8759 		if ((un->un_rsvd_status &
8760 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8761 			mutex_exit(ST_MUTEX);
8762 			rval = EACCES;
8763 			goto done;
8764 		}
8765 		rval = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
8766 		if (rval == EACCES) {
8767 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8768 			    "st_check_media: TUR got Reservation Conflict\n");
8769 			mutex_exit(ST_MUTEX);
8770 			goto done;
8771 		}
8772 		if (rval) {
8773 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8774 			    "st_check_media: TUR failed, going to retry\n");
8775 			un->un_mediastate = prev_state;
8776 			un->un_state = ST_STATE_OFFLINE;
8777 			goto retry;
8778 		}
8779 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8780 		    "st_check_media: media inserted\n");
8781 
8782 		/* this also rewinds the tape */
8783 		rval = st_tape_init(dev);
8784 		if (rval != 0) {
8785 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8786 			    "st_check_media : OFFLINE init failure ");
8787 			un->un_state = ST_STATE_OFFLINE;
8788 			un->un_pos.pmode = invalid;
8789 		} else {
8790 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8791 			un->un_pos.fileno = 0;
8792 			un->un_pos.blkno = 0;
8793 			un->un_pos.lgclblkno = 0;
8794 		}
8795 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8796 	    (un->un_state != ST_STATE_OFFLINE)) {
8797 		/*
8798 		 * supported devices must be rewound before ejection
8799 		 * rewind resets fileno & blkno
8800 		 */
8801 		un->un_laststate = un->un_state;
8802 		un->un_state = ST_STATE_OFFLINE;
8803 	}
8804 	mutex_exit(ST_MUTEX);
8805 done:
8806 	if (token) {
8807 		(void) scsi_watch_request_terminate(token,
8808 		    SCSI_WATCH_TERMINATE_WAIT);
8809 		mutex_enter(ST_MUTEX);
8810 		un->un_swr_token = (opaque_t)NULL;
8811 		mutex_exit(ST_MUTEX);
8812 	}
8813 
8814 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8815 
8816 	return (rval);
8817 }
8818 
8819 /*
8820  * st_media_watch_cb() is called by scsi_watch_thread for
8821  * verifying the request sense data (if any)
8822  */
8823 static int
8824 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8825 {
8826 	struct scsi_status *statusp = resultp->statusp;
8827 	struct scsi_extended_sense *sensep = resultp->sensep;
8828 	uchar_t actual_sense_length = resultp->actual_sense_length;
8829 	struct scsi_tape *un;
8830 	enum mtio_state state = MTIO_NONE;
8831 	int instance;
8832 	dev_t dev = (dev_t)arg;
8833 
8834 	instance = MTUNIT(dev);
8835 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8836 		return (-1);
8837 	}
8838 
8839 	mutex_enter(ST_MUTEX);
8840 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
8841 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8842 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8843 	    *((char *)statusp), (void *)sensep,
8844 	    actual_sense_length);
8845 
8846 
8847 	/*
8848 	 * if there was a check condition then sensep points to valid
8849 	 * sense data
8850 	 * if status was not a check condition but a reservation or busy
8851 	 * status then the new state is MTIO_NONE
8852 	 */
8853 	if (sensep) {
8854 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8855 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8856 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8857 
8858 		switch (un->un_dp->type) {
8859 		default:
8860 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8861 			    "st_media_watch_cb: unknown drive type %d, "
8862 			    "default to ST_TYPE_HP\n", un->un_dp->type);
8863 		/* FALLTHROUGH */
8864 
8865 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8866 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8867 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8868 			if (un->un_dp->type == ST_TYPE_FUJI) {
8869 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8870 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8871 			} else {
8872 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8873 				    "st_media_watch_cb: ST_TYPE_HP\n");
8874 			}
8875 			switch (sensep->es_key) {
8876 			case KEY_UNIT_ATTENTION:
8877 				/* not ready to ready transition */
8878 				/* hp/es_qual_code == 80 on>off>on */
8879 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8880 				if (sensep->es_add_code == 0x28) {
8881 					state = MTIO_INSERTED;
8882 				}
8883 				break;
8884 			case KEY_NOT_READY:
8885 				/* in process, rewinding or loading */
8886 				if ((sensep->es_add_code == 0x04) &&
8887 				    (sensep->es_qual_code == 0x00)) {
8888 					state = MTIO_EJECTED;
8889 				}
8890 				break;
8891 			}
8892 			break;
8893 
8894 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8895 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8896 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8897 			switch (sensep->es_key) {
8898 			case KEY_UNIT_ATTENTION:
8899 				/* operator medium removal request */
8900 				if ((sensep->es_add_code == 0x5a) &&
8901 				    (sensep->es_qual_code == 0x01)) {
8902 					state = MTIO_EJECTED;
8903 				/* not ready to ready transition */
8904 				} else if ((sensep->es_add_code == 0x28) &&
8905 				    (sensep->es_qual_code == 0x00)) {
8906 					state = MTIO_INSERTED;
8907 				}
8908 				break;
8909 			case KEY_NOT_READY:
8910 				/* medium not present */
8911 				if (sensep->es_add_code == 0x3a) {
8912 					state = MTIO_EJECTED;
8913 				}
8914 				break;
8915 			}
8916 			break;
8917 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8918 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8919 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8920 			switch (sensep->es_key) {
8921 			case KEY_NOT_READY:
8922 				if ((sensep->es_add_code == 0x04) &&
8923 				    (sensep->es_qual_code == 0x00)) {
8924 					/* volume not mounted? */
8925 					state = MTIO_EJECTED;
8926 				} else if (sensep->es_add_code == 0x3a) {
8927 					state = MTIO_EJECTED;
8928 				}
8929 				break;
8930 			case KEY_UNIT_ATTENTION:
8931 				state = MTIO_EJECTED;
8932 				break;
8933 			}
8934 			break;
8935 
8936 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8937 			switch (sensep->es_key) {
8938 			case KEY_UNIT_ATTENTION:
8939 				if (sensep->es_add_code == 0x28) {
8940 					state = MTIO_INSERTED;
8941 				}
8942 				break;
8943 			case KEY_NOT_READY:
8944 				if (sensep->es_add_code == 0x04) {
8945 					/* in transition but could be either */
8946 					state = un->un_specified_mediastate;
8947 				} else if ((sensep->es_add_code == 0x3a) &&
8948 				    (sensep->es_qual_code == 0x00)) {
8949 					state = MTIO_EJECTED;
8950 				}
8951 				break;
8952 			}
8953 			break;
8954 		}
8955 	} else if (*((char *)statusp) == STATUS_GOOD) {
8956 		state = MTIO_INSERTED;
8957 	}
8958 
8959 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8960 	    "st_media_watch_cb:state=%x, specified=%x\n",
8961 	    state, un->un_specified_mediastate);
8962 
8963 	/*
8964 	 * now signal the waiting thread if this is *not* the specified state;
8965 	 * delay the signal if the state is MTIO_INSERTED
8966 	 * to allow the target to recover
8967 	 */
8968 	if (state != un->un_specified_mediastate) {
8969 		un->un_mediastate = state;
8970 		if (state == MTIO_INSERTED) {
8971 			/*
8972 			 * delay the signal to give the drive a chance
8973 			 * to do what it apparently needs to do
8974 			 */
8975 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8976 			    "st_media_watch_cb:delayed cv_broadcast\n");
8977 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8978 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8979 		} else {
8980 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8981 			    "st_media_watch_cb:immediate cv_broadcast\n");
8982 			cv_broadcast(&un->un_state_cv);
8983 		}
8984 	}
8985 	mutex_exit(ST_MUTEX);
8986 	return (0);
8987 }
8988 
8989 /*
8990  * delayed cv_broadcast to allow for target to recover
8991  * from media insertion
8992  */
8993 static void
8994 st_delayed_cv_broadcast(void *arg)
8995 {
8996 	struct scsi_tape *un = arg;
8997 
8998 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
8999 
9000 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9001 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9002 
9003 	mutex_enter(ST_MUTEX);
9004 	cv_broadcast(&un->un_state_cv);
9005 	mutex_exit(ST_MUTEX);
9006 }
9007 
9008 /*
9009  * restart cmd currently at the start of the waitq
9010  */
9011 static void
9012 st_start_restart(void *arg)
9013 {
9014 	struct scsi_tape *un = arg;
9015 
9016 	ST_FUNC(ST_DEVINFO, st_start_restart);
9017 
9018 	ASSERT(un != NULL);
9019 
9020 	mutex_enter(ST_MUTEX);
9021 
9022 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9023 	    "st_tran_restart()\n");
9024 
9025 	if (un->un_quef) {
9026 		st_start(un);
9027 	}
9028 
9029 	mutex_exit(ST_MUTEX);
9030 }
9031 
9032 
9033 /*
9034  * Command completion processing
9035  *
9036  */
9037 static void
9038 st_intr(struct scsi_pkt *pkt)
9039 {
9040 	struct scsi_tape *un;
9041 	struct buf *last_runqf;
9042 	struct buf *bp;
9043 	int action = COMMAND_DONE;
9044 	clock_t	timout;
9045 	int	status;
9046 
9047 
9048 	bp = pkt->pkt_private;
9049 
9050 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9051 
9052 	ST_FUNC(ST_DEVINFO, st_intr);
9053 
9054 	mutex_enter(ST_MUTEX);
9055 
9056 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9057 
9058 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9059 
9060 	if (pkt->pkt_reason != CMD_CMPLT) {
9061 
9062 		/* If device has gone away not much else to do */
9063 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9064 			action = COMMAND_DONE_ERROR;
9065 		} else if (un->un_state == ST_STATE_SENSING) {
9066 			ST_DO_ERRSTATS(un, st_transerrs);
9067 			action = COMMAND_DONE_ERROR;
9068 		} else {
9069 			action = st_handle_incomplete(un, bp);
9070 		}
9071 	/*
9072 	 * At this point we know that the command was successfully
9073 	 * completed. Now what?
9074 	 */
9075 	} else if (un->un_arq_enabled &&
9076 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
9077 		/*
9078 		 * the transport layer successfully completed an autorqsense
9079 		 */
9080 		action = st_handle_autosense(un, bp);
9081 
9082 	} else if (un->un_state == ST_STATE_SENSING) {
9083 		/*
9084 		 * okay. We were running a REQUEST SENSE. Find
9085 		 * out what to do next.
9086 		 * some actions are based on un_state, hence
9087 		 * restore the state st was in before ST_STATE_SENSING.
9088 		 */
9089 		un->un_state = un->un_laststate;
9090 		action = st_handle_sense(un, bp);
9091 		/*
9092 		 * set pkt back to original packet in case we will have
9093 		 * to requeue it
9094 		 */
9095 		pkt = BP_PKT(bp);
9096 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
9097 		/*
9098 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9099 		 * to see if the status bits we're okay. If a request sense
9100 		 * is to be run, that will happen.
9101 		 */
9102 		action = st_check_error(un, pkt);
9103 	}
9104 
9105 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9106 		switch (action) {
9107 			case QUE_COMMAND:
9108 				/*
9109 				 * return cmd to head to the queue
9110 				 * since we are suspending so that
9111 				 * it gets restarted during resume
9112 				 */
9113 				if (un->un_runqf) {
9114 					last_runqf = un->un_runqf;
9115 					un->un_runqf = bp;
9116 					bp->b_actf = last_runqf;
9117 				} else {
9118 					bp->b_actf = NULL;
9119 					un->un_runqf = bp;
9120 					un->un_runql = bp;
9121 				}
9122 				action = JUST_RETURN;
9123 				break;
9124 
9125 			case QUE_SENSE:
9126 				action = COMMAND_DONE_ERROR;
9127 				break;
9128 
9129 			default:
9130 				break;
9131 		}
9132 	}
9133 
9134 	/*
9135 	 * Restore old state if we were sensing.
9136 	 */
9137 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9138 		un->un_state = un->un_laststate;
9139 	}
9140 
9141 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9142 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
9143 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
9144 
9145 
9146 	switch (action) {
9147 	case COMMAND_DONE_EACCES:
9148 		/* this is to report a reservation conflict */
9149 		st_bioerror(bp, EACCES);
9150 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9151 		    "Reservation Conflict \n");
9152 		un->un_pos.pmode = invalid;
9153 
9154 		/*FALLTHROUGH*/
9155 	case COMMAND_DONE_ERROR:
9156 		if (un->un_pos.eof < ST_EOT_PENDING &&
9157 		    un->un_state >= ST_STATE_OPEN) {
9158 			/*
9159 			 * all errors set state of the tape to 'unknown'
9160 			 * unless we're at EOT or are doing append testing.
9161 			 * If sense key was illegal request, preserve state.
9162 			 */
9163 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9164 				un->un_pos.pmode = invalid;
9165 			}
9166 		}
9167 
9168 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9169 		/*
9170 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9171 		 * make sure an error ocurrs, so make sure at least EIO is
9172 		 * returned
9173 		 */
9174 		if (geterror(bp) == 0)
9175 			st_bioerror(bp, EIO);
9176 
9177 		SET_PE_FLAG(un);
9178 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9179 		    (un->un_errno == EIO)) {
9180 			un->un_rqs_state &= ~(ST_RQS_VALID);
9181 		}
9182 		goto done;
9183 
9184 	case COMMAND_DONE_ERROR_RECOVERED:
9185 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9186 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9187 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9188 		if (geterror(bp) == 0) {
9189 			st_bioerror(bp, EIO);
9190 		}
9191 		SET_PE_FLAG(un);
9192 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9193 		    (un->un_errno == EIO)) {
9194 			un->un_rqs_state &= ~(ST_RQS_VALID);
9195 		}
9196 		/*FALLTHROUGH*/
9197 	case COMMAND_DONE:
9198 		st_set_state(un);
9199 done:
9200 		ST_DO_KSTATS(bp, kstat_runq_exit);
9201 		st_done_and_mutex_exit(un, bp);
9202 		return;
9203 
9204 	case QUE_SENSE:
9205 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9206 			goto sense_error;
9207 
9208 		if (un->un_state != ST_STATE_SENSING) {
9209 			un->un_laststate = un->un_state;
9210 			un->un_state = ST_STATE_SENSING;
9211 		}
9212 
9213 		un->un_rqs->pkt_private = (opaque_t)bp;
9214 		bzero(ST_RQSENSE, SENSE_LENGTH);
9215 
9216 		if (un->un_throttle) {
9217 			un->un_last_throttle = un->un_throttle;
9218 			un->un_throttle = 0;
9219 		}
9220 
9221 		mutex_exit(ST_MUTEX);
9222 
9223 		/*
9224 		 * never retry this, some other command will have nuked the
9225 		 * sense, anyway
9226 		 */
9227 		status = scsi_transport(un->un_rqs);
9228 
9229 		mutex_enter(ST_MUTEX);
9230 
9231 		if (un->un_last_throttle) {
9232 			un->un_throttle = un->un_last_throttle;
9233 		}
9234 
9235 		if (status == TRAN_ACCEPT) {
9236 			mutex_exit(ST_MUTEX);
9237 			return;
9238 		}
9239 		if (status != TRAN_BUSY)
9240 			ST_DO_ERRSTATS(un, st_transerrs);
9241 sense_error:
9242 		un->un_pos.pmode = invalid;
9243 		st_bioerror(bp, EIO);
9244 		SET_PE_FLAG(un);
9245 		goto done;
9246 
9247 	case QUE_BUSY_COMMAND:
9248 		/* longish timeout */
9249 		timout = ST_STATUS_BUSY_TIMEOUT;
9250 		goto que_it_up;
9251 
9252 	case QUE_COMMAND:
9253 		/* short timeout */
9254 		timout = ST_TRAN_BUSY_TIMEOUT;
9255 que_it_up:
9256 		/*
9257 		 * let st_handle_intr_busy put this bp back on waitq and make
9258 		 * checks to see if it is ok to requeue the command.
9259 		 */
9260 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9261 
9262 		/*
9263 		 * Save the throttle before setting up the timeout
9264 		 */
9265 		if (un->un_throttle) {
9266 			un->un_last_throttle = un->un_throttle;
9267 		}
9268 		mutex_exit(ST_MUTEX);
9269 		if (st_handle_intr_busy(un, bp, timout) == 0)
9270 			return;		/* timeout is setup again */
9271 
9272 		mutex_enter(ST_MUTEX);
9273 		un->un_pos.pmode = invalid;
9274 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9275 		st_bioerror(bp, EIO);
9276 		SET_PE_FLAG(un);
9277 		goto done;
9278 
9279 	case QUE_LAST_COMMAND:
9280 
9281 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9282 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9283 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9284 			goto last_command_error;
9285 		}
9286 		mutex_exit(ST_MUTEX);
9287 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9288 			return;
9289 		mutex_enter(ST_MUTEX);
9290 last_command_error:
9291 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9292 		un->un_pos.pmode = invalid;
9293 		st_bioerror(bp, EIO);
9294 		SET_PE_FLAG(un);
9295 		goto done;
9296 
9297 	case JUST_RETURN:
9298 	default:
9299 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9300 		mutex_exit(ST_MUTEX);
9301 		return;
9302 	}
9303 	/*NOTREACHED*/
9304 }
9305 
9306 static int
9307 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9308 {
9309 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9310 	int rval = COMMAND_DONE_ERROR;
9311 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9312 	    un->un_rqs : BP_PKT(bp);
9313 	int result;
9314 
9315 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9316 
9317 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9318 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9319 
9320 	ASSERT(mutex_owned(ST_MUTEX));
9321 
9322 	switch (pkt->pkt_reason) {
9323 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9324 		/*
9325 		 * this occurs when accessing a powered down drive, no
9326 		 * need to complain; just fail the open
9327 		 */
9328 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9329 
9330 		/*
9331 		 * if we have commands outstanding in HBA, and a command
9332 		 * comes back incomplete, we're hosed, so reset target
9333 		 * If we have the bus, but cmd_incomplete, we probably just
9334 		 * have a failed selection, so don't reset the target, just
9335 		 * requeue the command and try again
9336 		 */
9337 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9338 			goto reset_target;
9339 		}
9340 
9341 		/*
9342 		 * Retry selection a couple more times if we're
9343 		 * open.  If opening, we only try just once to
9344 		 * reduce probe time for nonexistant devices.
9345 		 */
9346 		if ((un->un_laststate > ST_STATE_OPENING) &&
9347 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
9348 			rval = QUE_COMMAND;
9349 		}
9350 		ST_DO_ERRSTATS(un, st_transerrs);
9351 		break;
9352 
9353 	case CMD_ABORTED:
9354 		/*
9355 		 * most likely this is caused by flush-on-error support. If
9356 		 * it was not there, the we're in trouble.
9357 		 */
9358 		if (!un->un_flush_on_errors) {
9359 			un->un_status = SUN_KEY_FATAL;
9360 			goto reset_target;
9361 		}
9362 
9363 		st_set_pe_errno(un);
9364 		bioerror(bp, un->un_errno);
9365 		if (un->un_errno)
9366 			return (COMMAND_DONE_ERROR);
9367 		else
9368 			return (COMMAND_DONE);
9369 
9370 	case CMD_TIMEOUT:	/* Command timed out */
9371 		un->un_status = SUN_KEY_TIMEOUT;
9372 
9373 		/*FALLTHROUGH*/
9374 	default:
9375 reset_target:
9376 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9377 		    "transport completed with %s\n",
9378 		    scsi_rname(pkt->pkt_reason));
9379 		ST_DO_ERRSTATS(un, st_transerrs);
9380 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9381 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9382 		    STAT_ABORTED)) == 0)) {
9383 
9384 			/*
9385 			 * If we haven't reserved the drive don't reset it.
9386 			 */
9387 			if ((un->un_rsvd_status &
9388 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9389 				return (rval);
9390 			}
9391 
9392 			/*
9393 			 * if we aren't lost yet we will be soon.
9394 			 */
9395 			un->un_pos.pmode = invalid;
9396 
9397 			mutex_exit(ST_MUTEX);
9398 
9399 			result = scsi_reset(ROUTE, RESET_TARGET);
9400 			/*
9401 			 * if target reset fails, then pull the chain
9402 			 */
9403 			if (result == 0) {
9404 				result = scsi_reset(ROUTE, RESET_ALL);
9405 			}
9406 			mutex_enter(ST_MUTEX);
9407 
9408 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9409 				/* no hope left to recover */
9410 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9411 				    "recovery by resets failed\n");
9412 				return (rval);
9413 			}
9414 		}
9415 	}
9416 
9417 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
9418 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
9419 		if ((un->un_rsvd_status & ST_RESERVE)) {
9420 			un->un_rsvd_status |= ST_LOST_RESERVE;
9421 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9422 			    "Lost Reservation\n");
9423 		}
9424 	}
9425 
9426 	if ((int)un->un_retry_ct++ < st_retry_count) {
9427 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9428 			rval = QUE_COMMAND;
9429 		} else if (bp == un->un_sbufp) {
9430 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
9431 			case SCMD_MODE_SENSE:
9432 			case SCMD_MODE_SELECT:
9433 			case SCMD_READ_BLKLIM:
9434 			case SCMD_REWIND:
9435 			case SCMD_LOAD:
9436 			case SCMD_TEST_UNIT_READY:
9437 				/*
9438 				 * These commands can be rerun with impunity
9439 				 */
9440 				rval = QUE_COMMAND;
9441 				break;
9442 
9443 			default:
9444 				break;
9445 			}
9446 		}
9447 	} else {
9448 		rval = COMMAND_DONE_ERROR;
9449 	}
9450 
9451 	if (un->un_state >= ST_STATE_OPEN) {
9452 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9453 		    fail, scsi_rname(pkt->pkt_reason),
9454 		    (rval == COMMAND_DONE_ERROR)?
9455 		    "giving up" : "retrying command");
9456 	}
9457 	return (rval);
9458 }
9459 
9460 /*
9461  * if the device is busy, then put this bp back on the waitq, on the
9462  * interrupt thread, where we want the head of the queue and not the
9463  * end
9464  *
9465  * The callers of this routine should take measures to save the
9466  * un_throttle in un_last_throttle which will be restored in
9467  * st_intr_restart(). The only exception should be st_intr_restart()
9468  * calling this routine for which the saving is already done.
9469  */
9470 static int
9471 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9472 	clock_t timeout_interval)
9473 {
9474 	struct buf *last_quef;
9475 	int rval = 0;
9476 
9477 	mutex_enter(ST_MUTEX);
9478 
9479 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
9480 
9481 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9482 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9483 
9484 	/*
9485 	 * Check to see if we hit the retry timeout. We check to make sure
9486 	 * this is the first one on the runq and make sure we have not
9487 	 * queued up any more, so this one has to be the last on the list
9488 	 * also. If it is not, we have to fail.  If it is not the first, but
9489 	 * is the last we are in trouble anyway, as we are in the interrupt
9490 	 * context here.
9491 	 */
9492 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9493 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9494 		rval = -1;
9495 		goto exit;
9496 	}
9497 
9498 	/* put the bp back on the waitq */
9499 	if (un->un_quef) {
9500 		last_quef = un->un_quef;
9501 		un->un_quef = bp;
9502 		bp->b_actf = last_quef;
9503 	} else  {
9504 		bp->b_actf = NULL;
9505 		un->un_quef = bp;
9506 		un->un_quel = bp;
9507 	}
9508 
9509 	/*
9510 	 * We know that this is the first and last on the runq at this time,
9511 	 * so we just nullify those two queues
9512 	 */
9513 	un->un_runqf = NULL;
9514 	un->un_runql = NULL;
9515 
9516 	/*
9517 	 * We don't want any other commands being started in the mean time.
9518 	 * If start had just released mutex after putting something on the
9519 	 * runq, we won't even get here.
9520 	 */
9521 	un->un_throttle = 0;
9522 
9523 	/*
9524 	 * send a marker pkt, if appropriate
9525 	 */
9526 	st_hba_unflush(un);
9527 
9528 	/*
9529 	 * all queues are aligned, we are just waiting to
9530 	 * transport
9531 	 */
9532 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9533 
9534 exit:
9535 	mutex_exit(ST_MUTEX);
9536 	return (rval);
9537 }
9538 
9539 /*
9540  * To get one error entry from error stack
9541  */
9542 static int
9543 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
9544 {
9545 #ifdef _MULTI_DATAMODEL
9546 	/*
9547 	 * For use when a 32 bit app makes a call into a
9548 	 * 64 bit ioctl
9549 	 */
9550 	struct mterror_entry32 err_entry32;
9551 #endif /* _MULTI_DATAMODEL */
9552 
9553 	int rval = 0;
9554 	struct mterror_entry err_entry;
9555 	struct mterror_entry_stack *err_link_entry_p;
9556 	size_t arq_status_len_in, arq_status_len_kr;
9557 
9558 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
9559 
9560 	ASSERT(mutex_owned(ST_MUTEX));
9561 
9562 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9563 	    "st_get_error_entry()\n");
9564 
9565 	/*
9566 	 * if error record stack empty, return ENXIO
9567 	 */
9568 	if (un->un_error_entry_stk == NULL) {
9569 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9570 		    "st_get_error_entry: Error Entry Stack Empty!\n");
9571 		rval = ENXIO;
9572 		goto ret;
9573 	}
9574 
9575 	/*
9576 	 * get the top entry from stack
9577 	 */
9578 	err_link_entry_p = un->un_error_entry_stk;
9579 	arq_status_len_kr =
9580 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
9581 
9582 #ifdef _MULTI_DATAMODEL
9583 	switch (ddi_model_convert_from(flag & FMODELS)) {
9584 	case DDI_MODEL_ILP32:
9585 		if (ddi_copyin((void *)arg, &err_entry32,
9586 		    MTERROR_ENTRY_SIZE_32, flag)) {
9587 			rval = EFAULT;
9588 			goto ret;
9589 		}
9590 
9591 		arq_status_len_in =
9592 		    (size_t)err_entry32.mtee_arq_status_len;
9593 
9594 		err_entry32.mtee_cdb_len =
9595 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
9596 
9597 		if (arq_status_len_in > arq_status_len_kr)
9598 			err_entry32.mtee_arq_status_len =
9599 			    (size32_t)arq_status_len_kr;
9600 
9601 		if (ddi_copyout(
9602 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9603 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
9604 		    err_entry32.mtee_cdb_len, flag)) {
9605 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9606 			    "st_get_error_entry: Copy cdb buffer error!");
9607 			rval = EFAULT;
9608 		}
9609 
9610 		if (ddi_copyout(
9611 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9612 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
9613 		    err_entry32.mtee_arq_status_len, flag)) {
9614 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9615 			    "st_get_error_entry: copy arq status error!");
9616 			rval = EFAULT;
9617 		}
9618 
9619 		if (ddi_copyout(&err_entry32, (void *)arg,
9620 		    MTERROR_ENTRY_SIZE_32, flag)) {
9621 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9622 			    "st_get_error_entry: copy arq status out error!");
9623 			rval = EFAULT;
9624 		}
9625 		break;
9626 
9627 	case DDI_MODEL_NONE:
9628 		if (ddi_copyin((void *)arg, &err_entry,
9629 		    MTERROR_ENTRY_SIZE_64, flag)) {
9630 			rval = EFAULT;
9631 			goto ret;
9632 		}
9633 		arq_status_len_in = err_entry.mtee_arq_status_len;
9634 
9635 		err_entry.mtee_cdb_len =
9636 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
9637 
9638 		if (arq_status_len_in > arq_status_len_kr)
9639 			err_entry.mtee_arq_status_len =
9640 			    arq_status_len_kr;
9641 
9642 		if (ddi_copyout(
9643 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9644 		    err_entry.mtee_cdb_buf,
9645 		    err_entry.mtee_cdb_len, flag)) {
9646 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9647 			    "st_get_error_entry: Copy cdb buffer error!");
9648 			rval = EFAULT;
9649 		}
9650 
9651 		if (ddi_copyout(
9652 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9653 		    err_entry.mtee_arq_status,
9654 		    err_entry.mtee_arq_status_len, flag)) {
9655 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9656 			    "st_get_error_entry: copy arq status error!");
9657 			rval = EFAULT;
9658 		}
9659 
9660 		if (ddi_copyout(&err_entry, (void *)arg,
9661 		    MTERROR_ENTRY_SIZE_64, flag)) {
9662 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9663 			    "st_get_error_entry: copy arq status out error!");
9664 			rval = EFAULT;
9665 		}
9666 		break;
9667 	}
9668 #else /* _MULTI_DATAMODEL */
9669 	if (ddi_copyin((void *)arg, &err_entry,
9670 	    MTERROR_ENTRY_SIZE_64, flag)) {
9671 		rval = EFAULT;
9672 		goto ret;
9673 	}
9674 	arq_status_len_in = err_entry.mtee_arq_status_len;
9675 
9676 	err_entry.mtee_cdb_len =
9677 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
9678 
9679 	if (arq_status_len_in > arq_status_len_kr)
9680 		err_entry.mtee_arq_status_len =
9681 		    arq_status_len_kr;
9682 
9683 	if (ddi_copyout(
9684 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9685 	    err_entry.mtee_cdb_buf,
9686 	    err_entry.mtee_cdb_len, flag)) {
9687 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9688 		    "st_get_error_entry: Copy cdb buffer error!");
9689 		rval = EFAULT;
9690 	}
9691 
9692 	if (ddi_copyout(
9693 	    err_link_entry_p->mtees_entry.mtee_arq_status,
9694 	    err_entry.mtee_arq_status,
9695 	    err_entry.mtee_arq_status_len, flag)) {
9696 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9697 		    "st_get_error_entry: copy arq status buffer error!");
9698 		rval = EFAULT;
9699 	}
9700 
9701 	if (ddi_copyout(&err_entry, (void *)arg,
9702 	    MTERROR_ENTRY_SIZE_64, flag)) {
9703 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9704 		    "st_get_error_entry: copy arq status out error!");
9705 		rval = EFAULT;
9706 	}
9707 #endif /* _MULTI_DATAMODEL */
9708 
9709 	/*
9710 	 * update stack
9711 	 */
9712 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
9713 
9714 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
9715 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
9716 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
9717 
9718 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
9719 	    SECMDS_STATUS_SIZE);
9720 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
9721 
9722 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
9723 	err_link_entry_p = NULL;
9724 ret:
9725 	return (rval);
9726 }
9727 
9728 /*
9729  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
9730  * the scsi CDB command which causes the error and generates sense data and
9731  * the scsi status.
9732  *
9733  *      error-record stack
9734  *
9735  *
9736  *             TOP                                     BOTTOM
9737  *              ------------------------------------------
9738  *              |   0   |   1   |   2   |   ...  |   n   |
9739  *              ------------------------------------------
9740  *                  ^
9741  *                  |
9742  *       pointer to error entry
9743  *
9744  * when st driver generates one sense data record, it creates a error-entry
9745  * and pushes it onto the stack.
9746  *
9747  */
9748 
9749 static void
9750 st_update_error_stack(struct scsi_tape *un,
9751 			struct scsi_pkt *pkt,
9752 			struct scsi_arq_status *cmd)
9753 {
9754 	struct mterror_entry_stack *err_entry_tmp;
9755 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
9756 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
9757 
9758 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
9759 
9760 	ASSERT(mutex_owned(ST_MUTEX));
9761 
9762 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9763 	    "st_update_error_stack()\n");
9764 
9765 	ASSERT(cmd);
9766 	ASSERT(cdbp);
9767 	if (cdblen == 0) {
9768 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9769 		    "st_update_error_stack: CDB length error!\n");
9770 		return;
9771 	}
9772 
9773 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
9774 	ASSERT(err_entry_tmp != NULL);
9775 
9776 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
9777 	    kmem_alloc(cdblen, KM_SLEEP);
9778 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
9779 
9780 	err_entry_tmp->mtees_entry.mtee_arq_status =
9781 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
9782 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
9783 
9784 	/*
9785 	 * copy cdb command & length to current error entry
9786 	 */
9787 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
9788 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
9789 
9790 	/*
9791 	 * copy scsi status length to current error entry
9792 	 */
9793 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
9794 	    SECMDS_STATUS_SIZE;
9795 
9796 	/*
9797 	 * copy sense data and scsi status to current error entry
9798 	 */
9799 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
9800 	    SECMDS_STATUS_SIZE);
9801 
9802 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
9803 	un->un_error_entry_stk = err_entry_tmp;
9804 
9805 }
9806 
9807 /*
9808  * Empty all the error entry in stack
9809  */
9810 static void
9811 st_empty_error_stack(struct scsi_tape *un)
9812 {
9813 	struct mterror_entry_stack *linkp;
9814 
9815 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
9816 
9817 	ASSERT(mutex_owned(ST_MUTEX));
9818 
9819 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9820 	    "st_empty_entry_stack()\n");
9821 
9822 	while (un->un_error_entry_stk != NULL) {
9823 		linkp = un->un_error_entry_stk;
9824 		un->un_error_entry_stk =
9825 		    un->un_error_entry_stk->mtees_nextp;
9826 
9827 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
9828 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
9829 			    linkp->mtees_entry.mtee_cdb_len);
9830 
9831 		if (linkp->mtees_entry.mtee_arq_status != NULL)
9832 			kmem_free(linkp->mtees_entry.mtee_arq_status,
9833 			    linkp->mtees_entry.mtee_arq_status_len);
9834 
9835 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
9836 		linkp = NULL;
9837 	}
9838 }
9839 
9840 static int
9841 st_handle_sense(struct scsi_tape *un, struct buf *bp)
9842 {
9843 	struct scsi_pkt *pkt = BP_PKT(bp);
9844 	struct scsi_pkt *rqpkt = un->un_rqs;
9845 	struct scsi_arq_status arqstat;
9846 
9847 	int rval = COMMAND_DONE_ERROR;
9848 	int amt;
9849 
9850 	ST_FUNC(ST_DEVINFO, st_handle_sense);
9851 
9852 	ASSERT(mutex_owned(ST_MUTEX));
9853 
9854 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9855 	    "st_handle_sense()\n");
9856 
9857 	if (SCBP(rqpkt)->sts_busy) {
9858 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9859 		    "busy unit on request sense\n");
9860 		if ((int)un->un_retry_ct++ < st_retry_count) {
9861 			rval = QUE_BUSY_COMMAND;
9862 		}
9863 		return (rval);
9864 	} else if (SCBP(rqpkt)->sts_chk) {
9865 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9866 		    "Check Condition on REQUEST SENSE\n");
9867 		return (rval);
9868 	}
9869 
9870 	/* was there enough data? */
9871 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
9872 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
9873 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9874 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9875 		    "REQUEST SENSE couldn't get sense data\n");
9876 		return (rval);
9877 	}
9878 
9879 	bcopy(SCBP(pkt), &arqstat.sts_status,
9880 	    sizeof (struct scsi_status));
9881 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
9882 	    sizeof (struct scsi_status));
9883 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
9884 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
9885 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
9886 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
9887 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
9888 
9889 	/*
9890 	 * copy one arqstat entry in the sense data buffer
9891 	 */
9892 	st_update_error_stack(un, pkt, &arqstat);
9893 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
9894 }
9895 
9896 static int
9897 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
9898 {
9899 	struct scsi_pkt *pkt = BP_PKT(bp);
9900 	struct scsi_arq_status *arqstat =
9901 	    (struct scsi_arq_status *)pkt->pkt_scbp;
9902 	int rval = COMMAND_DONE_ERROR;
9903 	int amt;
9904 
9905 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
9906 
9907 	ASSERT(mutex_owned(ST_MUTEX));
9908 
9909 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9910 	    "st_handle_autosense()\n");
9911 
9912 	if (arqstat->sts_rqpkt_status.sts_busy) {
9913 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9914 		    "busy unit on request sense\n");
9915 		/*
9916 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
9917 		 * the disadvantage is that we do not have any delay for the
9918 		 * second retry of rqsense and we have to keep a packet around
9919 		 */
9920 		return (QUE_SENSE);
9921 
9922 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
9923 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9924 		    "transport error on REQUEST SENSE\n");
9925 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
9926 		    ((arqstat->sts_rqpkt_statistics &
9927 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
9928 			mutex_exit(ST_MUTEX);
9929 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9930 				/*
9931 				 * if target reset fails, then pull the chain
9932 				 */
9933 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
9934 					ST_DEBUG6(ST_DEVINFO, st_label,
9935 					    CE_WARN,
9936 					    "recovery by resets failed\n");
9937 				}
9938 			}
9939 			mutex_enter(ST_MUTEX);
9940 		}
9941 		return (rval);
9942 
9943 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
9944 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9945 		    "Check Condition on REQUEST SENSE\n");
9946 		return (rval);
9947 	}
9948 
9949 
9950 	/* was there enough data? */
9951 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9952 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
9953 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9954 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9955 		    "REQUEST SENSE couldn't get sense data\n");
9956 		return (rval);
9957 	}
9958 
9959 	/*
9960 	 * copy one arqstat entry in the sense data buffer
9961 	 */
9962 	st_update_error_stack(un, pkt, arqstat);
9963 
9964 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
9965 
9966 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
9967 }
9968 
9969 static int
9970 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
9971 	struct scsi_status *statusp)
9972 {
9973 	struct scsi_pkt *pkt = BP_PKT(bp);
9974 	int rval = COMMAND_DONE_ERROR;
9975 	long resid;
9976 	struct scsi_extended_sense *sensep = ST_RQSENSE;
9977 	int severity;
9978 	int get_error;
9979 
9980 	ST_FUNC(ST_DEVINFO, st_decode_sense);
9981 
9982 	ASSERT(mutex_owned(ST_MUTEX));
9983 
9984 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9985 	    "st_decode_sense()\n");
9986 
9987 	/*
9988 	 * For uscsi commands, squirrel away a copy of the
9989 	 * results of the Request Sense.
9990 	 */
9991 	if (USCSI_CMD(bp)) {
9992 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9993 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
9994 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
9995 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
9996 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
9997 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
9998 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9999 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10000 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10001 		}
10002 	}
10003 
10004 	/*
10005 	 * If the drive is an MT-02, reposition the
10006 	 * secondary error code into the proper place.
10007 	 *
10008 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10009 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10010 	 * so it's in byte 12.
10011 	 */
10012 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10013 		sensep->es_code = sensep->es_add_info[0];
10014 	}
10015 
10016 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10017 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10018 
10019 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
10020 	    sizeof (*sensep));
10021 
10022 	/* for normal I/O check extract the resid values. */
10023 	if (bp != un->un_sbufp) {
10024 		if (sensep->es_valid) {
10025 			resid =
10026 			    (sensep->es_info_1 << 24) |
10027 			    (sensep->es_info_2 << 16) |
10028 			    (sensep->es_info_3 << 8)  |
10029 			    (sensep->es_info_4);
10030 			/* If fixed block */
10031 			if (un->un_bsize) {
10032 				resid *= un->un_bsize;
10033 			}
10034 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10035 			resid = pkt->pkt_resid;
10036 		} else {
10037 			resid = bp->b_bcount;
10038 		}
10039 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10040 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
10041 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10042 		    resid,
10043 		    (sensep->es_info_1 << 24) |
10044 		    (sensep->es_info_2 << 16) |
10045 		    (sensep->es_info_3 << 8)  |
10046 		    (sensep->es_info_4),
10047 		    pkt->pkt_resid);
10048 		/*
10049 		 * The problem is, what should we believe?
10050 		 */
10051 		if (resid && (pkt->pkt_resid == 0)) {
10052 			pkt->pkt_resid = resid;
10053 		}
10054 	} else {
10055 		/*
10056 		 * If the command is SCMD_SPACE, we need to get the
10057 		 * residual as returned in the sense data, to adjust
10058 		 * our idea of current tape position correctly
10059 		 */
10060 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10061 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10062 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10063 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
10064 		    (sensep->es_valid)) {
10065 			resid =
10066 			    (sensep->es_info_1 << 24) |
10067 			    (sensep->es_info_2 << 16) |
10068 			    (sensep->es_info_3 << 8)  |
10069 			    (sensep->es_info_4);
10070 			bp->b_resid = resid;
10071 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10072 			    "st_handle_sense(other):	resid=%ld\n", resid);
10073 		} else {
10074 			/*
10075 			 * If the special command is SCMD_READ,
10076 			 * the correct resid will be set later.
10077 			 */
10078 			resid = bp->b_bcount;
10079 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10080 			    "st_handle_sense(special read):  resid=%ld\n",
10081 			    resid);
10082 		}
10083 	}
10084 
10085 	if ((un->un_state >= ST_STATE_OPEN) &&
10086 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10087 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10088 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10089 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10090 		    "sense data", (char *)sensep, amt);
10091 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10092 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10093 		    bp->b_bcount, resid, pkt->pkt_resid);
10094 	}
10095 
10096 	switch (un->un_status = sensep->es_key) {
10097 	case KEY_NO_SENSE:
10098 		severity = SCSI_ERR_INFO;
10099 
10100 		/*
10101 		 * Erase, locate or rewind operation in progress, retry
10102 		 * ASC  ASCQ
10103 		 *  00   18    Erase operation in progress
10104 		 *  00   19    Locate operation in progress
10105 		 *  00   1A    Rewind operation in progress
10106 		 */
10107 		if (sensep->es_add_code == 0 &&
10108 		    ((sensep->es_qual_code == 0x18) ||
10109 		    (sensep->es_qual_code == 0x19) ||
10110 		    (sensep->es_qual_code == 0x1a))) {
10111 			rval = QUE_COMMAND;
10112 			break;
10113 		}
10114 
10115 		goto common;
10116 
10117 	case KEY_RECOVERABLE_ERROR:
10118 		severity = SCSI_ERR_RECOVERED;
10119 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10120 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10121 			if (un->un_dp->options &
10122 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10123 				rval = QUE_LAST_COMMAND;
10124 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10125 				    severity, un->un_pos.lgclblkno,
10126 				    un->un_err_pos.lgclblkno, scsi_cmds,
10127 				    sensep);
10128 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10129 				    "Command will be retried\n");
10130 			} else {
10131 				severity = SCSI_ERR_FATAL;
10132 				rval = COMMAND_DONE_ERROR_RECOVERED;
10133 				ST_DO_ERRSTATS(un, st_softerrs);
10134 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10135 				    severity, un->un_pos.lgclblkno,
10136 				    un->un_err_pos.lgclblkno, scsi_cmds,
10137 				    sensep);
10138 			}
10139 			break;
10140 		}
10141 common:
10142 		/*
10143 		 * XXX only want reads to be stopped by filemarks.
10144 		 * Don't want them to be stopped by EOT.  EOT matters
10145 		 * only on write.
10146 		 */
10147 		if (sensep->es_filmk && !sensep->es_eom) {
10148 			rval = COMMAND_DONE;
10149 		} else if (sensep->es_eom) {
10150 			rval = COMMAND_DONE;
10151 		} else if (sensep->es_ili) {
10152 			/*
10153 			 * Fun with variable length record devices:
10154 			 * for specifying larger blocks sizes than the
10155 			 * actual physical record size.
10156 			 */
10157 			if (un->un_bsize == 0 && resid > 0) {
10158 				/*
10159 				 * XXX! Ugly.
10160 				 * The requested blocksize is > tape blocksize,
10161 				 * so this is ok, so we just return the
10162 				 * actual size xferred.
10163 				 */
10164 				pkt->pkt_resid = resid;
10165 				rval = COMMAND_DONE;
10166 			} else if (un->un_bsize == 0 && resid < 0) {
10167 				/*
10168 				 * The requested blocksize is < tape blocksize,
10169 				 * so this is not ok, so we err with ENOMEM
10170 				 */
10171 				rval = COMMAND_DONE_ERROR_RECOVERED;
10172 				st_bioerror(bp, ENOMEM);
10173 			} else {
10174 				ST_DO_ERRSTATS(un, st_softerrs);
10175 				severity = SCSI_ERR_FATAL;
10176 				rval = COMMAND_DONE_ERROR;
10177 				st_bioerror(bp, EINVAL);
10178 			}
10179 		} else {
10180 			/*
10181 			 * we hope and pray for this just being
10182 			 * something we can ignore (ie. a
10183 			 * truly recoverable soft error)
10184 			 */
10185 			rval = COMMAND_DONE;
10186 		}
10187 		if (sensep->es_filmk) {
10188 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10189 			    "filemark\n");
10190 			un->un_status = SUN_KEY_EOF;
10191 			un->un_pos.eof = ST_EOF_PENDING;
10192 			SET_PE_FLAG(un);
10193 		}
10194 
10195 		/*
10196 		 * ignore eom when reading, a fmk should terminate reading
10197 		 */
10198 		if ((sensep->es_eom) &&
10199 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10200 			if ((sensep->es_add_code == 0) &&
10201 			    (sensep->es_qual_code == 4)) {
10202 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10203 				    "bot\n");
10204 				un->un_status = SUN_KEY_BOT;
10205 				un->un_pos.eof = ST_NO_EOF;
10206 				un->un_pos.lgclblkno = 0;
10207 				un->un_pos.fileno = 0;
10208 				un->un_pos.blkno = 0;
10209 				un->un_pos.pmode = legacy;
10210 			} else {
10211 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10212 				    "eom\n");
10213 				un->un_status = SUN_KEY_EOT;
10214 				un->un_pos.eof = ST_EOM;
10215 			}
10216 			SET_PE_FLAG(un);
10217 		}
10218 
10219 		break;
10220 
10221 	case KEY_ILLEGAL_REQUEST:
10222 
10223 		if (un->un_laststate >= ST_STATE_OPEN) {
10224 			ST_DO_ERRSTATS(un, st_softerrs);
10225 			severity = SCSI_ERR_FATAL;
10226 		} else {
10227 			severity = SCSI_ERR_INFO;
10228 		}
10229 		break;
10230 
10231 	case KEY_MEDIUM_ERROR:
10232 		ST_DO_ERRSTATS(un, st_harderrs);
10233 		severity = SCSI_ERR_FATAL;
10234 
10235 		/*
10236 		 * for (buffered) writes, a medium error must be fatal
10237 		 */
10238 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
10239 			rval = COMMAND_DONE_ERROR_RECOVERED;
10240 		}
10241 
10242 check_keys:
10243 		/*
10244 		 * attempt to process the keys in the presence of
10245 		 * other errors
10246 		 */
10247 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10248 			/*
10249 			 * Fun with variable length record devices:
10250 			 * for specifying larger blocks sizes than the
10251 			 * actual physical record size.
10252 			 */
10253 			if (un->un_bsize == 0 && resid > 0) {
10254 				/*
10255 				 * XXX! Ugly
10256 				 */
10257 				pkt->pkt_resid = resid;
10258 			} else if (un->un_bsize == 0 && resid < 0) {
10259 				st_bioerror(bp, EINVAL);
10260 			} else {
10261 				severity = SCSI_ERR_FATAL;
10262 				rval = COMMAND_DONE_ERROR;
10263 				st_bioerror(bp, EINVAL);
10264 			}
10265 		}
10266 		if (sensep->es_filmk) {
10267 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10268 			    "filemark\n");
10269 			un->un_status = SUN_KEY_EOF;
10270 			un->un_pos.eof = ST_EOF_PENDING;
10271 			SET_PE_FLAG(un);
10272 		}
10273 
10274 		/*
10275 		 * ignore eom when reading, a fmk should terminate reading
10276 		 */
10277 		if ((sensep->es_eom) &&
10278 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10279 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10280 			un->un_status = SUN_KEY_EOT;
10281 			un->un_pos.eof = ST_EOM;
10282 			SET_PE_FLAG(un);
10283 		}
10284 
10285 		break;
10286 
10287 	case KEY_VOLUME_OVERFLOW:
10288 		ST_DO_ERRSTATS(un, st_softerrs);
10289 		un->un_pos.eof = ST_EOM;
10290 		severity = SCSI_ERR_FATAL;
10291 		rval = COMMAND_DONE_ERROR;
10292 		goto check_keys;
10293 
10294 	case KEY_HARDWARE_ERROR:
10295 		ST_DO_ERRSTATS(un, st_harderrs);
10296 		severity = SCSI_ERR_FATAL;
10297 		rval = COMMAND_DONE_ERROR;
10298 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10299 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10300 		break;
10301 
10302 	case KEY_BLANK_CHECK:
10303 		ST_DO_ERRSTATS(un, st_softerrs);
10304 		severity = SCSI_ERR_INFO;
10305 
10306 		/*
10307 		 * if not a special request and some data was xferred then it
10308 		 * it is not an error yet
10309 		 */
10310 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10311 			/*
10312 			 * no error for read with or without data xferred
10313 			 */
10314 			un->un_status = SUN_KEY_EOT;
10315 			un->un_pos.eof = ST_EOT;
10316 			rval = COMMAND_DONE_ERROR;
10317 			SET_PE_FLAG(un);
10318 			goto check_keys;
10319 		} else if (bp != un->un_sbufp &&
10320 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10321 			rval = COMMAND_DONE;
10322 		} else {
10323 			rval = COMMAND_DONE_ERROR_RECOVERED;
10324 		}
10325 
10326 		if (un->un_laststate >= ST_STATE_OPEN) {
10327 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10328 			    "blank check\n");
10329 			un->un_pos.eof = ST_EOM;
10330 		}
10331 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10332 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10333 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10334 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10335 			/*
10336 			 * we were doing a fast forward by skipping
10337 			 * multiple fmk at the time
10338 			 */
10339 			st_bioerror(bp, EIO);
10340 			severity = SCSI_ERR_RECOVERED;
10341 			rval	 = COMMAND_DONE;
10342 		}
10343 		SET_PE_FLAG(un);
10344 		goto check_keys;
10345 
10346 	case KEY_WRITE_PROTECT:
10347 		if (st_wrongtapetype(un)) {
10348 			un->un_status = SUN_KEY_WRONGMEDIA;
10349 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10350 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
10351 			severity = SCSI_ERR_UNKNOWN;
10352 		} else {
10353 			severity = SCSI_ERR_FATAL;
10354 		}
10355 		ST_DO_ERRSTATS(un, st_harderrs);
10356 		rval = COMMAND_DONE_ERROR;
10357 		st_bioerror(bp, EACCES);
10358 		break;
10359 
10360 	case KEY_UNIT_ATTENTION:
10361 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10362 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10363 
10364 		/*
10365 		 * If we have detected a Bus Reset and the tape
10366 		 * drive has been reserved.
10367 		 */
10368 		if (ST_RQSENSE->es_add_code == 0x29 &&
10369 		    (un->un_rsvd_status & ST_RESERVE)) {
10370 			un->un_rsvd_status |= ST_LOST_RESERVE;
10371 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10372 			    "st_decode_sense: Lost Reservation\n");
10373 		}
10374 
10375 		if (un->un_state <= ST_STATE_OPENING) {
10376 			/*
10377 			 * Look, the tape isn't open yet, now determine
10378 			 * if the cause is a BUS RESET, Save the file and
10379 			 * Block positions for the callers to recover from
10380 			 * the loss of position.
10381 			 */
10382 			if (un->un_pos.pmode != invalid) {
10383 				if (ST_RQSENSE->es_add_code == 0x29) {
10384 					un->un_save_fileno = un->un_pos.fileno;
10385 					un->un_save_blkno = un->un_pos.blkno;
10386 					un->un_restore_pos = 1;
10387 				}
10388 			}
10389 
10390 			if ((int)un->un_retry_ct++ < st_retry_count) {
10391 				rval = QUE_COMMAND;
10392 			} else {
10393 				rval = COMMAND_DONE_ERROR;
10394 			}
10395 			severity = SCSI_ERR_INFO;
10396 
10397 		} else {
10398 			/*
10399 			 * Check if it is an Unexpected Unit Attention.
10400 			 * If state is >= ST_STATE_OPEN, we have
10401 			 * already done the initialization .
10402 			 * In this case it is Fatal Error
10403 			 * since no further reading/writing
10404 			 * can be done with fileno set to < 0.
10405 			 */
10406 			if (un->un_state >= ST_STATE_OPEN) {
10407 				ST_DO_ERRSTATS(un, st_harderrs);
10408 				severity = SCSI_ERR_FATAL;
10409 			} else {
10410 				severity = SCSI_ERR_INFO;
10411 			}
10412 			rval = COMMAND_DONE_ERROR;
10413 		}
10414 		un->un_pos.pmode = invalid;
10415 
10416 		break;
10417 
10418 	case KEY_NOT_READY:
10419 		/*
10420 		 * If in process of getting ready retry.
10421 		 */
10422 		if (sensep->es_add_code  == 0x04 &&
10423 		    sensep->es_qual_code == 0x01 &&
10424 		    un->un_retry_ct++ < st_retry_count) {
10425 			rval = QUE_COMMAND;
10426 			severity = SCSI_ERR_INFO;
10427 		} else {
10428 			/* give up */
10429 			rval = COMMAND_DONE_ERROR;
10430 			severity = SCSI_ERR_FATAL;
10431 		}
10432 
10433 		/*
10434 		 * If this was an error and after device opened
10435 		 * do error stats.
10436 		 */
10437 		if (rval == COMMAND_DONE_ERROR &&
10438 		    un->un_state > ST_STATE_OPENING) {
10439 			ST_DO_ERRSTATS(un, st_harderrs);
10440 		}
10441 
10442 		if (ST_RQSENSE->es_add_code == 0x3a) {
10443 			if (st_error_level >= SCSI_ERR_FATAL)
10444 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10445 				    "Tape not inserted in drive\n");
10446 			un->un_mediastate = MTIO_EJECTED;
10447 			cv_broadcast(&un->un_state_cv);
10448 		}
10449 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
10450 		    (rval != QUE_COMMAND))
10451 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10452 		break;
10453 
10454 	case KEY_ABORTED_COMMAND:
10455 
10456 		/*
10457 		 * Probably a parity error...
10458 		 * if we retry here then this may cause data to be
10459 		 * written twice or data skipped during reading
10460 		 */
10461 		ST_DO_ERRSTATS(un, st_harderrs);
10462 		severity = SCSI_ERR_FATAL;
10463 		rval = COMMAND_DONE_ERROR;
10464 		goto check_keys;
10465 
10466 	default:
10467 		/*
10468 		 * Undecoded sense key.	 Try retries and hope
10469 		 * that will fix the problem.  Otherwise, we're
10470 		 * dead.
10471 		 */
10472 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10473 		    "Unhandled Sense Key '%s'\n",
10474 		    sense_keys[un->un_status]);
10475 		ST_DO_ERRSTATS(un, st_harderrs);
10476 		severity = SCSI_ERR_FATAL;
10477 		rval = COMMAND_DONE_ERROR;
10478 		goto check_keys;
10479 	}
10480 
10481 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
10482 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
10483 	    (un->un_laststate > ST_STATE_OPENING) &&
10484 	    (severity >= st_error_level))) {
10485 
10486 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
10487 		    un->un_pos.lgclblkno, un->un_err_pos.lgclblkno,
10488 		    scsi_cmds, sensep);
10489 		if (sensep->es_filmk) {
10490 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10491 			    "File Mark Detected\n");
10492 		}
10493 		if (sensep->es_eom) {
10494 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10495 			    "End-of-Media Detected\n");
10496 		}
10497 		if (sensep->es_ili) {
10498 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10499 			    "Incorrect Length Indicator Set\n");
10500 		}
10501 	}
10502 	get_error = geterror(bp);
10503 	if (((rval == COMMAND_DONE_ERROR) ||
10504 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
10505 	    ((get_error == EIO) || (get_error == 0))) {
10506 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
10507 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
10508 		if (un->un_rqs_state & ST_RQS_READ) {
10509 			un->un_rqs_state &= ~(ST_RQS_READ);
10510 		} else {
10511 			un->un_rqs_state |= ST_RQS_OVR;
10512 		}
10513 	}
10514 
10515 	return (rval);
10516 }
10517 
10518 
10519 static int
10520 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
10521 {
10522 	int status = TRAN_ACCEPT;
10523 
10524 	mutex_enter(ST_MUTEX);
10525 
10526 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
10527 
10528 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10529 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
10530 
10531 	/*
10532 	 * Check to see if we hit the retry timeout. We check to make sure
10533 	 * this is the first one on the runq and make sure we have not
10534 	 * queued up any more, so this one has to be the last on the list
10535 	 * also. If it is not, we have to fail.  If it is not the first, but
10536 	 * is the last we are in trouble anyway, as we are in the interrupt
10537 	 * context here.
10538 	 */
10539 	if (((int)un->un_retry_ct > st_retry_count) ||
10540 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
10541 		goto exit;
10542 	}
10543 
10544 	if (un->un_throttle) {
10545 		un->un_last_throttle = un->un_throttle;
10546 		un->un_throttle = 0;
10547 	}
10548 
10549 	/*
10550 	 * Here we know : bp is the first and last one on the runq
10551 	 * it is not necessary to put it back on the head of the
10552 	 * waitq and then move from waitq to runq. Save this queuing
10553 	 * and call scsi_transport.
10554 	 */
10555 
10556 	mutex_exit(ST_MUTEX);
10557 
10558 	status = scsi_transport(BP_PKT(bp));
10559 
10560 	mutex_enter(ST_MUTEX);
10561 
10562 	if (status == TRAN_ACCEPT) {
10563 		un->un_tran_retry_ct = 0;
10564 		if (un->un_last_throttle) {
10565 			un->un_throttle = un->un_last_throttle;
10566 		}
10567 		mutex_exit(ST_MUTEX);
10568 
10569 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10570 		    "restart transport \n");
10571 		return (0);
10572 	}
10573 
10574 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
10575 	mutex_exit(ST_MUTEX);
10576 
10577 	if (status == TRAN_BUSY) {
10578 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
10579 			return (0);
10580 		}
10581 	}
10582 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10583 	    "restart transport rejected\n");
10584 	mutex_enter(ST_MUTEX);
10585 	ST_DO_ERRSTATS(un, st_transerrs);
10586 	if (un->un_last_throttle) {
10587 		un->un_throttle = un->un_last_throttle;
10588 	}
10589 exit:
10590 	mutex_exit(ST_MUTEX);
10591 	return (-1);
10592 }
10593 
10594 static int
10595 st_wrongtapetype(struct scsi_tape *un)
10596 {
10597 
10598 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
10599 
10600 	ASSERT(mutex_owned(ST_MUTEX));
10601 
10602 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
10603 
10604 	/*
10605 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
10606 	 */
10607 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
10608 		switch (un->un_dp->type) {
10609 		case ST_TYPE_WANGTEK:
10610 		case ST_TYPE_ARCHIVE:
10611 			/*
10612 			 * If this really worked, we could go off of
10613 			 * the density codes set in the modesense
10614 			 * page. For this drive, 0x10 == QIC-120,
10615 			 * 0xf == QIC-150, and 0x5 should be for
10616 			 * both QIC-24 and, maybe, QIC-11. However,
10617 			 * the h/w doesn't do what the manual says
10618 			 * that it should, so we'll key off of
10619 			 * getting a WRITE PROTECT error AND wp *not*
10620 			 * set in the mode sense information.
10621 			 */
10622 			/*
10623 			 * XXX but we already know that status is
10624 			 * write protect, so don't check it again.
10625 			 */
10626 
10627 			if (un->un_status == KEY_WRITE_PROTECT &&
10628 			    un->un_mspl->wp == 0) {
10629 				return (1);
10630 			}
10631 			break;
10632 		default:
10633 			break;
10634 		}
10635 	}
10636 	return (0);
10637 }
10638 
10639 static int
10640 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
10641 {
10642 	int action;
10643 
10644 	ST_FUNC(ST_DEVINFO, st_check_error);
10645 
10646 	ASSERT(mutex_owned(ST_MUTEX));
10647 
10648 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
10649 
10650 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
10651 		action = COMMAND_DONE_EACCES;
10652 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
10653 	} else if (SCBP(pkt)->sts_busy) {
10654 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
10655 		if ((int)un->un_retry_ct++ < st_retry_count) {
10656 			action = QUE_BUSY_COMMAND;
10657 		} else if ((un->un_rsvd_status &
10658 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10659 			/*
10660 			 * If this is a command done before reserve is done
10661 			 * don't reset.
10662 			 */
10663 			action = COMMAND_DONE_ERROR;
10664 		} else {
10665 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10666 			    "unit busy too long\n");
10667 			mutex_exit(ST_MUTEX);
10668 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
10669 				(void) scsi_reset(ROUTE, RESET_ALL);
10670 			}
10671 			mutex_enter(ST_MUTEX);
10672 			action = COMMAND_DONE_ERROR;
10673 		}
10674 	} else if (SCBP(pkt)->sts_chk) {
10675 		/*
10676 		 * we should only get here if the auto rqsense failed
10677 		 * thru a uscsi cmd without autorequest sense
10678 		 * so we just try again
10679 		 */
10680 		action = QUE_SENSE;
10681 	} else {
10682 		action = COMMAND_DONE;
10683 	}
10684 	return (action);
10685 }
10686 
10687 static void
10688 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
10689 {
10690 	int nblks;
10691 
10692 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
10693 
10694 	ASSERT(mutex_owned(ST_MUTEX));
10695 
10696 	/* If variable block mode */
10697 	if (un->un_bsize == 0) {
10698 		nblks = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
10699 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid) / ONE_K;
10700 	} else {
10701 		nblks = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
10702 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
10703 	}
10704 	un->un_pos.blkno += nblks;
10705 	un->un_pos.lgclblkno += nblks;
10706 }
10707 
10708 static void
10709 st_set_state(struct scsi_tape *un)
10710 {
10711 	struct buf *bp = un->un_runqf;
10712 	struct scsi_pkt *sp = BP_PKT(bp);
10713 	struct uscsi_cmd *ucmd;
10714 
10715 	ST_FUNC(ST_DEVINFO, st_set_state);
10716 
10717 	ASSERT(mutex_owned(ST_MUTEX));
10718 
10719 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10720 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
10721 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
10722 
10723 	if (bp != un->un_sbufp) {
10724 #ifdef STDEBUG
10725 		if (DEBUGGING && sp->pkt_resid) {
10726 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10727 			    "pkt_resid %ld bcount %ld\n",
10728 			    sp->pkt_resid, bp->b_bcount);
10729 		}
10730 #endif
10731 		bp->b_resid = sp->pkt_resid;
10732 		st_calc_bnum(un, bp);
10733 		if (bp->b_flags & B_READ) {
10734 			un->un_lastop = ST_OP_READ;
10735 			un->un_fmneeded = 0;
10736 		} else {
10737 			un->un_lastop = ST_OP_WRITE;
10738 			if (un->un_dp->options & ST_REEL) {
10739 				un->un_fmneeded = 2;
10740 			} else {
10741 				un->un_fmneeded = 1;
10742 			}
10743 		}
10744 		/*
10745 		 * all is honky dory at this point, so let's
10746 		 * readjust the throttle, to increase speed, if we
10747 		 * have not throttled down.
10748 		 */
10749 		if (un->un_throttle) {
10750 			un->un_throttle = un->un_max_throttle;
10751 		}
10752 	} else {
10753 		optype new_lastop;
10754 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
10755 
10756 		un->un_lastop = ST_OP_CTL;
10757 
10758 		switch (cmd) {
10759 		case SCMD_WRITE:
10760 			bp->b_resid = sp->pkt_resid;
10761 			new_lastop = ST_OP_WRITE;
10762 			st_calc_bnum(un, bp);
10763 			if (un->un_dp->options & ST_REEL) {
10764 				un->un_fmneeded = 2;
10765 			} else {
10766 				un->un_fmneeded = 1;
10767 			}
10768 			break;
10769 		case SCMD_READ:
10770 			bp->b_resid = sp->pkt_resid;
10771 			new_lastop = ST_OP_READ;
10772 			st_calc_bnum(un, bp);
10773 			un->un_fmneeded = 0;
10774 			break;
10775 		case SCMD_WRITE_FILE_MARK:
10776 		{
10777 			int fmdone;
10778 
10779 			if (un->un_pos.eof != ST_EOM) {
10780 				un->un_pos.eof = ST_NO_EOF;
10781 			}
10782 			fmdone = (bp->b_bcount - bp->b_resid);
10783 			if (fmdone > 0) {
10784 				un->un_lastop = new_lastop = ST_OP_WEOF;
10785 				un->un_pos.lgclblkno += fmdone;
10786 				un->un_pos.fileno += fmdone;
10787 				un->un_pos.blkno = 0;
10788 			} else {
10789 				new_lastop = ST_OP_CTL;
10790 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
10791 				    "Flushed buffer\n");
10792 			}
10793 			if (fmdone > un->un_fmneeded) {
10794 				un->un_fmneeded = 0;
10795 			} else {
10796 				un->un_fmneeded -= fmdone;
10797 			}
10798 			break;
10799 		}
10800 		case SCMD_REWIND:
10801 			un->un_pos.eof = ST_NO_EOF;
10802 			un->un_pos.fileno = 0;
10803 			un->un_pos.blkno = 0;
10804 			un->un_pos.lgclblkno = 0;
10805 			un->un_pos.pmode = legacy;
10806 			new_lastop = ST_OP_CTL;
10807 			break;
10808 
10809 		case SCMD_SPACE:
10810 		{
10811 			int count;
10812 			long resid;
10813 			int done;
10814 
10815 			count = (int)SPACE_CNT(bp->b_bcount);
10816 			/* if was a uscsi space cmd b_bcount == 0 */
10817 			if (count == 0) {
10818 				count =
10819 				    (sp->pkt_cdbp[2] << 16) |
10820 				    (sp->pkt_cdbp[3] << 8)  |
10821 				    (sp->pkt_cdbp[4]);
10822 			}
10823 			resid = (long)SPACE_CNT(bp->b_resid);
10824 			if (count >= 0) {
10825 				done = (count - resid);
10826 			} else {
10827 				done = ((-count) - resid);
10828 			}
10829 			if (done > 0) {
10830 				un->un_lastop = new_lastop = ST_OP_CTL;
10831 			} else {
10832 				new_lastop = ST_OP_CTL;
10833 			}
10834 
10835 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
10836 			    "space cmd: cdb[1] = %s\n"
10837 			    "space data:       = 0x%lx\n"
10838 			    "space count:      = %d\n"
10839 			    "space resid:      = %ld\n"
10840 			    "spaces done:      = %d\n"
10841 			    "fileno before     = %d\n"
10842 			    "blkno before      = %d\n",
10843 			    space_strs[sp->pkt_cdbp[1] & 7],
10844 			    bp->b_bcount,
10845 			    count, resid, done,
10846 			    un->un_pos.fileno, un->un_pos.blkno);
10847 
10848 			switch (sp->pkt_cdbp[1]) {
10849 			case SPACE_TYPE(SP_FLM):
10850 				/* Space file forward */
10851 				if (count >= 0) {
10852 					if (un->un_pos.eof <= ST_EOF) {
10853 						un->un_pos.eof = ST_NO_EOF;
10854 					}
10855 					un->un_pos.fileno += done;
10856 					un->un_pos.blkno = 0;
10857 					break;
10858 				}
10859 				/* Space file backward */
10860 				if (done > un->un_pos.fileno) {
10861 					un->un_pos.fileno = 0;
10862 					un->un_pos.blkno = 0;
10863 				} else {
10864 					un->un_pos.fileno -= done;
10865 					un->un_pos.blkno = INF;
10866 				}
10867 				break;
10868 			case SPACE_TYPE(SP_BLK):
10869 				/* Space block forward */
10870 				if (count >= 0) {
10871 					un->un_pos.blkno += done;
10872 					break;
10873 				}
10874 				/* Space block backward */
10875 				if (un->un_pos.eof >= ST_EOF_PENDING) {
10876 				/*
10877 				 * we stepped back into
10878 				 * a previous file; we are not
10879 				 * making an effort to pretend that
10880 				 * we are still in the current file
10881 				 * ie. logical == physical position
10882 				 * and leave it to st_ioctl to correct
10883 				 */
10884 					if (done > un->un_pos.blkno) {
10885 						un->un_pos.blkno = 0;
10886 					} else {
10887 						un->un_pos.fileno--;
10888 						un->un_pos.blkno = INF;
10889 					}
10890 				} else {
10891 					un->un_pos.blkno -= done;
10892 				}
10893 				break;
10894 			case SPACE_TYPE(SP_SQFLM):
10895 				un->un_pos.pmode = logical;
10896 				un->un_pos.blkno = 0;
10897 				un->un_lastop = new_lastop = ST_OP_CTL;
10898 				break;
10899 			case SPACE_TYPE(SP_EOD):
10900 				un->un_pos.pmode = logical;
10901 				un->un_pos.eof = ST_EOM;
10902 				un->un_status = KEY_BLANK_CHECK;
10903 				break;
10904 			default:
10905 				un->un_pos.pmode = invalid;
10906 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
10907 				    "Unsupported space cmd: %s\n",
10908 				    space_strs[sp->pkt_cdbp[1] & 7]);
10909 
10910 				un->un_lastop = new_lastop = ST_OP_CTL;
10911 			}
10912 
10913 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10914 			    "after_space rs %ld fil %d blk %d\n",
10915 			    resid, un->un_pos.fileno, un->un_pos.blkno);
10916 
10917 			break;
10918 		}
10919 		case SCMD_LOAD:
10920 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
10921 				un->un_pos.fileno = 0;
10922 				un->un_pos.pmode = legacy;
10923 			} else {
10924 				un->un_state = ST_STATE_OFFLINE;
10925 				un->un_pos.pmode = invalid;
10926 			}
10927 			un->un_density_known = 0;
10928 			un->un_pos.eof = ST_NO_EOF;
10929 			un->un_pos.blkno = 0;
10930 			un->un_lastop = new_lastop = ST_OP_CTL;
10931 			break;
10932 		case SCMD_ERASE:
10933 			un->un_pos.eof = ST_NO_EOF;
10934 			un->un_pos.blkno = 0;
10935 			un->un_pos.fileno = 0;
10936 			un->un_pos.lgclblkno = 0;
10937 			un->un_pos.pmode = legacy;
10938 			new_lastop = ST_OP_CTL;
10939 			break;
10940 		case SCMD_RESERVE:
10941 			un->un_rsvd_status |= ST_RESERVE;
10942 			un->un_rsvd_status &=
10943 			    ~(ST_RELEASE | ST_LOST_RESERVE |
10944 			    ST_RESERVATION_CONFLICT);
10945 			new_lastop = un->un_lastop;
10946 			break;
10947 		case SCMD_RELEASE:
10948 			un->un_rsvd_status |= ST_RELEASE;
10949 			un->un_rsvd_status &=
10950 			    ~(ST_RESERVE | ST_LOST_RESERVE |
10951 			    ST_RESERVATION_CONFLICT);
10952 			new_lastop = ST_OP_CTL;
10953 			break;
10954 		case SCMD_PERSISTENT_RESERVE_IN:
10955 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10956 			    "PGR_IN command\n");
10957 			break;
10958 		case SCMD_PERSISTENT_RESERVE_OUT:
10959 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
10960 			case ST_SA_SCSI3_RESERVE:
10961 			case ST_SA_SCSI3_PREEMPT:
10962 			case ST_SA_SCSI3_PREEMPTANDABORT:
10963 				un->un_rsvd_status |=
10964 				    ST_APPLICATION_RESERVATIONS;
10965 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10966 				    "PGR Reserve and set: entering"
10967 				    " ST_APPLICATION_RESERVATIONS mode");
10968 				break;
10969 			case ST_SA_SCSI3_RELEASE:
10970 			case ST_SA_SCSI3_CLEAR:
10971 				un->un_rsvd_status &=
10972 				    ~ST_APPLICATION_RESERVATIONS;
10973 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10974 				    "PGR Release and reset: exiting"
10975 				    " ST_APPLICATION_RESERVATIONS mode");
10976 				break;
10977 			}
10978 			break;
10979 		case SCMD_TEST_UNIT_READY:
10980 		case SCMD_READ_BLKLIM:
10981 		case SCMD_REQUEST_SENSE:
10982 		case SCMD_INQUIRY:
10983 		case SCMD_RECOVER_BUF:
10984 		case SCMD_MODE_SELECT:
10985 		case SCMD_MODE_SENSE:
10986 		case SCMD_DOORLOCK:
10987 		case SCMD_READ_BUFFER:
10988 		case SCMD_REPORT_DENSITIES:
10989 		case SCMD_LOG_SELECT_G1:
10990 		case SCMD_LOG_SENSE_G1:
10991 		case SCMD_REPORT_LUNS:
10992 		case SCMD_READ_ATTRIBUTE:
10993 		case SCMD_READ_MEDIA_SERIAL:
10994 			new_lastop = ST_OP_CTL;
10995 			break;
10996 		case SCMD_READ_POSITION:
10997 			new_lastop = ST_OP_CTL;
10998 			if (USCSI_CMD(bp)) {
10999 				(void) st_get_read_pos(un, bp);
11000 			}
11001 			break;
11002 		case SCMD_LOCATE:
11003 		case SCMD_LOCATE_G4:
11004 			/* Locate makes position mode no longer legacy */
11005 			un->un_lastop = new_lastop = ST_OP_CTL;
11006 			break;
11007 		default:
11008 			/*
11009 			 * Unknown command, If was USCSI and USCSI_SILENT
11010 			 * flag was not set, set position to unknown.
11011 			 */
11012 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11013 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11014 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11015 				    "unknown cmd 0x%X caused loss of state\n",
11016 				    cmd);
11017 			} else {
11018 				break;
11019 			}
11020 			/* FALLTHROUGH */
11021 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11022 			un->un_pos.pmode = invalid;
11023 			un->un_lastop = new_lastop = ST_OP_CTL;
11024 			break;
11025 		}
11026 
11027 		/* new_lastop should have been changed */
11028 		ASSERT(new_lastop != ST_OP_NIL);
11029 
11030 		/* If un_lastop should copy new_lastop  */
11031 		if (((un->un_lastop == ST_OP_WRITE) ||
11032 		    (un->un_lastop == ST_OP_WEOF)) &&
11033 		    new_lastop != ST_OP_CTL) {
11034 			un->un_lastop = new_lastop;
11035 		}
11036 	}
11037 
11038 	/*
11039 	 * In the st driver we have a logical and physical file position.
11040 	 * Under BSD behavior, when you get a zero read, the logical position
11041 	 * is before the filemark but after the last record of the file.
11042 	 * The physical position is after the filemark. MTIOCGET should always
11043 	 * return the logical file position.
11044 	 *
11045 	 * The next read gives a silent skip to the next file.
11046 	 * Under SVR4, the logical file position remains before the filemark
11047 	 * until the file is closed or a space operation is performed.
11048 	 * Hence set err_resid and err_file before changing fileno if case
11049 	 * BSD Behaviour.
11050 	 */
11051 	un->un_err_resid = bp->b_resid;
11052 	COPY_POS(&un->un_err_pos, &un->un_pos);
11053 	un->un_retry_ct = 0;
11054 
11055 
11056 	/*
11057 	 * If we've seen a filemark via the last read operation
11058 	 * advance the file counter, but mark things such that
11059 	 * the next read operation gets a zero count. We have
11060 	 * to put this here to handle the case of sitting right
11061 	 * at the end of a tape file having seen the file mark,
11062 	 * but the tape is closed and then re-opened without
11063 	 * any further i/o. That is, the position information
11064 	 * must be updated before a close.
11065 	 */
11066 
11067 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11068 		/*
11069 		 * If we're a 1/2" tape, and we get a filemark
11070 		 * right on block 0, *AND* we were not in the
11071 		 * first file on the tape, and we've hit logical EOM.
11072 		 * We'll mark the state so that later we do the
11073 		 * right thing (in st_close(), st_strategy() or
11074 		 * st_ioctl()).
11075 		 *
11076 		 */
11077 		if ((un->un_dp->options & ST_REEL) &&
11078 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11079 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11080 			un->un_pos.eof = ST_EOT_PENDING;
11081 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11082 			    "eot pending\n");
11083 			un->un_pos.fileno++;
11084 			un->un_pos.blkno = 0;
11085 		} else if (BSD_BEHAVIOR) {
11086 			/*
11087 			 * If the read of the filemark was a side effect
11088 			 * of reading some blocks (i.e., data was actually
11089 			 * read), then the EOF mark is pending and the
11090 			 * bump into the next file awaits the next read
11091 			 * operation (which will return a zero count), or
11092 			 * a close or a space operation, else the bump
11093 			 * into the next file occurs now.
11094 			 */
11095 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11096 			    "resid=%lx, bcount=%lx\n",
11097 			    bp->b_resid, bp->b_bcount);
11098 
11099 			if (bp->b_resid != bp->b_bcount) {
11100 				un->un_pos.eof = ST_EOF;
11101 			} else {
11102 				un->un_silent_skip = 1;
11103 				un->un_pos.eof = ST_NO_EOF;
11104 				un->un_pos.fileno++;
11105 				un->un_pos.lgclblkno++;
11106 				un->un_save_blkno = un->un_pos.blkno;
11107 				un->un_pos.blkno = 0;
11108 			}
11109 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11110 			    "eof of file %d, eof=%d\n",
11111 			    un->un_pos.fileno, un->un_pos.eof);
11112 		} else if (SVR4_BEHAVIOR) {
11113 			/*
11114 			 * If the read of the filemark was a side effect
11115 			 * of reading some blocks (i.e., data was actually
11116 			 * read), then the next read should return 0
11117 			 */
11118 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11119 			    "resid=%lx, bcount=%lx\n",
11120 			    bp->b_resid, bp->b_bcount);
11121 			if (bp->b_resid == bp->b_bcount) {
11122 				un->un_pos.eof = ST_EOF;
11123 			}
11124 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11125 			    "eof of file=%d, eof=%d\n",
11126 			    un->un_pos.fileno, un->un_pos.eof);
11127 		}
11128 	}
11129 }
11130 
11131 /*
11132  * set the correct un_errno, to take corner cases into consideration
11133  */
11134 static void
11135 st_set_pe_errno(struct scsi_tape *un)
11136 {
11137 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
11138 
11139 	ASSERT(mutex_owned(ST_MUTEX));
11140 
11141 	/* if errno is already set, don't reset it */
11142 	if (un->un_errno)
11143 		return;
11144 
11145 	/* here un_errno == 0 */
11146 	/*
11147 	 * if the last transfer before flushing all the
11148 	 * waiting I/O's, was 0 (resid = count), then we
11149 	 * want to give the user an error on all the rest,
11150 	 * so here.  If there was a transfer, we set the
11151 	 * resid and counts to 0, and let it drop through,
11152 	 * giving a zero return.  the next I/O will then
11153 	 * give an error.
11154 	 */
11155 	if (un->un_last_resid == un->un_last_count) {
11156 		switch (un->un_pos.eof) {
11157 		case ST_EOM:
11158 			un->un_errno = ENOMEM;
11159 			break;
11160 		case ST_EOT:
11161 		case ST_EOF:
11162 			un->un_errno = EIO;
11163 			break;
11164 		}
11165 	} else {
11166 		/*
11167 		 * we know they did not have a zero, so make
11168 		 * sure they get one
11169 		 */
11170 		un->un_last_resid = un->un_last_count = 0;
11171 	}
11172 }
11173 
11174 
11175 /*
11176  * send in a marker pkt to terminate flushing of commands by BBA (via
11177  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
11178  */
11179 static void
11180 st_hba_unflush(struct scsi_tape *un)
11181 {
11182 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
11183 
11184 	ASSERT(mutex_owned(ST_MUTEX));
11185 
11186 	if (!un->un_flush_on_errors)
11187 		return;
11188 
11189 #ifdef FLUSH_ON_ERRORS
11190 
11191 	if (!un->un_mkr_pkt) {
11192 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
11193 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
11194 
11195 		/* we slept, so it must be there */
11196 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
11197 	}
11198 
11199 	mutex_exit(ST_MUTEX);
11200 	scsi_transport(un->un_mkr_pkt);
11201 	mutex_enter(ST_MUTEX);
11202 #endif
11203 }
11204 
11205 static char *
11206 st_print_scsi_cmd(char cmd)
11207 {
11208 	char tmp[64];
11209 	char *cpnt;
11210 
11211 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
11212 	/* tmp goes out of scope on return and caller sees garbage */
11213 	if (cpnt == tmp) {
11214 		cpnt = "Unknown Command";
11215 	}
11216 	return (cpnt);
11217 }
11218 
11219 static void
11220 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
11221     char *title, char *cdb)
11222 {
11223 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
11224 	char buf[256];
11225 	int instance = ddi_get_instance(dip);
11226 	struct scsi_tape *un;
11227 
11228 	un = ddi_get_soft_state(st_state, instance);
11229 
11230 	ST_FUNC(dip, st_print_cdb);
11231 
11232 #ifdef DEBUG
11233 	if ((st_debug & 0x180) == 0x100) {
11234 		scsi_log(dip, label, level, "node %s cmd %s\n",
11235 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
11236 		return;
11237 	}
11238 #endif
11239 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
11240 	st_clean_print(dip, label, level, buf, cdb, len);
11241 }
11242 
11243 static void
11244 st_clean_print(dev_info_t *dev, char *label, uint_t level,
11245     char *title, char *data, int len)
11246 {
11247 	int	i;
11248 	int 	c;
11249 	char	*format;
11250 	char	buf[256];
11251 	uchar_t	byte;
11252 
11253 	ST_FUNC(dev, st_clean_print);
11254 
11255 	(void) sprintf(buf, "%s:\n", title);
11256 	scsi_log(dev, label, level, "%s", buf);
11257 	level = CE_CONT;
11258 	for (i = 0; i < len; ) {
11259 		buf[0] = 0;
11260 		for (c = 0; c < 8 && i < len; c++, i++) {
11261 			byte = (uchar_t)data[i];
11262 			if (byte < 0x10)
11263 				format = "0x0%x ";
11264 			else
11265 				format = "0x%x ";
11266 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
11267 		}
11268 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
11269 
11270 		scsi_log(dev, label, level, "%s\n", buf);
11271 	}
11272 }
11273 
11274 /*
11275  * Conditionally enabled debugging
11276  */
11277 #ifdef	STDEBUG
11278 static void
11279 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
11280 {
11281 	char tmpbuf[64];
11282 
11283 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
11284 
11285 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11286 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
11287 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
11288 	    count, count,
11289 	    wait == ASYNC_CMD ? "a" : "");
11290 }
11291 
11292 /*
11293  * Returns pointer to name of minor node name of device 'dev'.
11294  */
11295 static char *
11296 st_dev_name(dev_t dev)
11297 {
11298 	struct scsi_tape *un;
11299 	const char density[] = { 'l', 'm', 'h', 'c' };
11300 	static char name[4];
11301 	minor_t minor;
11302 	int instance;
11303 	int nprt = 0;
11304 
11305 	minor = getminor(dev);
11306 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
11307 	un = ddi_get_soft_state(st_state, instance);
11308 	if (un) {
11309 		ST_FUNC(ST_DEVINFO, st_dev_name);
11310 	}
11311 
11312 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
11313 
11314 	if (minor & MT_BSD) {
11315 		name[++nprt] = 'b';
11316 	}
11317 
11318 	if (minor & MT_NOREWIND) {
11319 		name[++nprt] = 'n';
11320 	}
11321 
11322 	/* NULL terminator */
11323 	name[++nprt] = 0;
11324 
11325 	return (name);
11326 }
11327 #endif	/* STDEBUG */
11328 
11329 /*
11330  * Soft error reporting, so far unique to each drive
11331  *
11332  * Currently supported: exabyte and DAT soft error reporting
11333  */
11334 static int
11335 st_report_exabyte_soft_errors(dev_t dev, int flag)
11336 {
11337 	uchar_t *sensep;
11338 	int amt;
11339 	int rval = 0;
11340 	char cdb[CDB_GROUP0], *c = cdb;
11341 	struct uscsi_cmd *com;
11342 
11343 	GET_SOFT_STATE(dev);
11344 
11345 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
11346 
11347 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11348 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
11349 	    dev, flag);
11350 
11351 	ASSERT(mutex_owned(ST_MUTEX));
11352 
11353 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11354 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
11355 
11356 	*c++ = SCMD_REQUEST_SENSE;
11357 	*c++ = 0;
11358 	*c++ = 0;
11359 	*c++ = 0;
11360 	*c++ = TAPE_SENSE_LENGTH;
11361 	/*
11362 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
11363 	 */
11364 	*c   = (char)0x80;
11365 
11366 	com->uscsi_cdb = cdb;
11367 	com->uscsi_cdblen = CDB_GROUP0;
11368 	com->uscsi_bufaddr = (caddr_t)sensep;
11369 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
11370 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11371 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11372 
11373 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11374 	if (rval || com->uscsi_status) {
11375 		goto done;
11376 	}
11377 
11378 	/*
11379 	 * was there enough data?
11380 	 */
11381 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
11382 
11383 	if ((amt >= 19) && un->un_kbytes_xferred) {
11384 		uint_t count, error_rate;
11385 		uint_t rate;
11386 
11387 		if (sensep[21] & CLN) {
11388 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11389 			    "Periodic head cleaning required");
11390 		}
11391 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
11392 			goto done;
11393 		}
11394 		/*
11395 		 * check if soft error reporting needs to be done.
11396 		 */
11397 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
11398 		count &= 0xffffff;
11399 		error_rate = (count * 100)/un->un_kbytes_xferred;
11400 
11401 #ifdef	STDEBUG
11402 		if (st_soft_error_report_debug) {
11403 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11404 			    "Exabyte Soft Error Report:\n");
11405 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11406 			    "read/write error counter: %d\n", count);
11407 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11408 			    "number of bytes transferred: %dK\n",
11409 			    un->un_kbytes_xferred);
11410 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11411 			    "error_rate: %d%%\n", error_rate);
11412 
11413 			if (amt >= 22) {
11414 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11415 				    "unit sense: 0x%b 0x%b 0x%b\n",
11416 				    sensep[19], SENSE_19_BITS,
11417 				    sensep[20], SENSE_20_BITS,
11418 				    sensep[21], SENSE_21_BITS);
11419 			}
11420 			if (amt >= 27) {
11421 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11422 				    "tracking retry counter: %d\n",
11423 				    sensep[26]);
11424 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11425 				    "read/write retry counter: %d\n",
11426 				    sensep[27]);
11427 			}
11428 		}
11429 #endif
11430 
11431 		if (flag & FWRITE) {
11432 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
11433 		} else {
11434 			rate = EXABYTE_READ_ERROR_THRESHOLD;
11435 		}
11436 		if (error_rate >= rate) {
11437 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11438 			    "Soft error rate (%d%%) during %s was too high",
11439 			    error_rate,
11440 			    ((flag & FWRITE) ? wrg_str : rdg_str));
11441 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11442 			    "Please, replace tape cartridge\n");
11443 		}
11444 	}
11445 
11446 done:
11447 	kmem_free(com, sizeof (*com));
11448 	kmem_free(sensep, TAPE_SENSE_LENGTH);
11449 
11450 	if (rval != 0) {
11451 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11452 		    "exabyte soft error reporting failed\n");
11453 	}
11454 	return (rval);
11455 }
11456 
11457 /*
11458  * this is very specific to Archive 4mm dat
11459  */
11460 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
11461 
11462 static int
11463 st_report_dat_soft_errors(dev_t dev, int flag)
11464 {
11465 	uchar_t *sensep;
11466 	int amt, i;
11467 	int rval = 0;
11468 	char cdb[CDB_GROUP1], *c = cdb;
11469 	struct uscsi_cmd *com;
11470 
11471 	GET_SOFT_STATE(dev);
11472 
11473 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
11474 
11475 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11476 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11477 
11478 	ASSERT(mutex_owned(ST_MUTEX));
11479 
11480 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11481 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11482 
11483 	*c++ = SCMD_LOG_SENSE_G1;
11484 	*c++ = 0;
11485 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
11486 	*c++ = 0;
11487 	*c++ = 0;
11488 	*c++ = 0;
11489 	*c++ = 2;
11490 	*c++ = 0;
11491 	*c++ = (char)LOG_SENSE_LENGTH;
11492 	*c   = 0;
11493 	com->uscsi_cdb    = cdb;
11494 	com->uscsi_cdblen  = CDB_GROUP1;
11495 	com->uscsi_bufaddr = (caddr_t)sensep;
11496 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
11497 	com->uscsi_flags   =
11498 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11499 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11500 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11501 	if (rval) {
11502 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11503 		    "DAT soft error reporting failed\n");
11504 	}
11505 	if (rval || com->uscsi_status) {
11506 		goto done;
11507 	}
11508 
11509 	/*
11510 	 * was there enough data?
11511 	 */
11512 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
11513 
11514 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
11515 		int total, retries, param_code;
11516 
11517 		total = -1;
11518 		retries = -1;
11519 		amt = sensep[3] + 4;
11520 
11521 
11522 #ifdef STDEBUG
11523 		if (st_soft_error_report_debug) {
11524 			(void) printf("logsense:");
11525 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
11526 				if (i % 16 == 0) {
11527 					(void) printf("\t\n");
11528 				}
11529 				(void) printf(" %x", sensep[i]);
11530 			}
11531 			(void) printf("\n");
11532 		}
11533 #endif
11534 
11535 		/*
11536 		 * parse the param_codes
11537 		 */
11538 		if (sensep[0] == 2 || sensep[0] == 3) {
11539 			for (i = 4; i < amt; i++) {
11540 				param_code = (sensep[i++] << 8);
11541 				param_code += sensep[i++];
11542 				i++; /* skip control byte */
11543 				if (param_code == 5) {
11544 					if (sensep[i++] == 4) {
11545 						total = (sensep[i++] << 24);
11546 						total += (sensep[i++] << 16);
11547 						total += (sensep[i++] << 8);
11548 						total += sensep[i];
11549 					}
11550 				} else if (param_code == 0x8007) {
11551 					if (sensep[i++] == 2) {
11552 						retries = sensep[i++] << 8;
11553 						retries += sensep[i];
11554 					}
11555 				} else {
11556 					i += sensep[i];
11557 				}
11558 			}
11559 		}
11560 
11561 		/*
11562 		 * if the log sense returned valid numbers then determine
11563 		 * the read and write error thresholds based on the amount of
11564 		 * data transferred
11565 		 */
11566 
11567 		if (total > 0 && retries > 0) {
11568 			short normal_retries = 0;
11569 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
11570 			    "total xferred (%s) =%x, retries=%x\n",
11571 			    ((flag & FWRITE) ? wrg_str : rdg_str),
11572 			    total, retries);
11573 
11574 			if (flag & FWRITE) {
11575 				if (total <=
11576 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
11577 					normal_retries =
11578 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
11579 				} else {
11580 					normal_retries =
11581 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
11582 				}
11583 			} else {
11584 				if (total <=
11585 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
11586 					normal_retries =
11587 					    DAT_SMALL_READ_ERROR_THRESHOLD;
11588 				} else {
11589 					normal_retries =
11590 					    DAT_LARGE_READ_ERROR_THRESHOLD;
11591 				}
11592 			}
11593 
11594 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
11595 			"normal retries=%d\n", normal_retries);
11596 
11597 			if (retries >= normal_retries) {
11598 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11599 				    "Soft error rate (retries = %d) during "
11600 				    "%s was too high",  retries,
11601 				    ((flag & FWRITE) ? wrg_str : rdg_str));
11602 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11603 				    "Periodic head cleaning required "
11604 				    "and/or replace tape cartridge\n");
11605 			}
11606 
11607 		} else if (total == -1 || retries == -1) {
11608 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11609 			    "log sense parameter code does not make sense\n");
11610 		}
11611 	}
11612 
11613 	/*
11614 	 * reset all values
11615 	 */
11616 	c = cdb;
11617 	*c++ = SCMD_LOG_SELECT_G1;
11618 	*c++ = 2;	/* this resets all values */
11619 	*c++ = (char)0xc0;
11620 	*c++ = 0;
11621 	*c++ = 0;
11622 	*c++ = 0;
11623 	*c++ = 0;
11624 	*c++ = 0;
11625 	*c++ = 0;
11626 	*c   = 0;
11627 	com->uscsi_bufaddr = NULL;
11628 	com->uscsi_buflen  = 0;
11629 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
11630 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11631 	if (rval) {
11632 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11633 		    "DAT soft error reset failed\n");
11634 	}
11635 done:
11636 	kmem_free(com, sizeof (*com));
11637 	kmem_free(sensep, LOG_SENSE_LENGTH);
11638 	return (rval);
11639 }
11640 
11641 static int
11642 st_report_soft_errors(dev_t dev, int flag)
11643 {
11644 	GET_SOFT_STATE(dev);
11645 
11646 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
11647 
11648 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11649 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11650 
11651 	ASSERT(mutex_owned(ST_MUTEX));
11652 
11653 	switch (un->un_dp->type) {
11654 	case ST_TYPE_EXB8500:
11655 	case ST_TYPE_EXABYTE:
11656 		return (st_report_exabyte_soft_errors(dev, flag));
11657 		/*NOTREACHED*/
11658 	case ST_TYPE_PYTHON:
11659 		return (st_report_dat_soft_errors(dev, flag));
11660 		/*NOTREACHED*/
11661 	default:
11662 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
11663 		return (-1);
11664 	}
11665 }
11666 
11667 /*
11668  * persistent error routines
11669  */
11670 
11671 /*
11672  * enable persistent errors, and set the throttle appropriately, checking
11673  * for flush-on-errors capability
11674  */
11675 static void
11676 st_turn_pe_on(struct scsi_tape *un)
11677 {
11678 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
11679 
11680 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
11681 	ASSERT(mutex_owned(ST_MUTEX));
11682 
11683 	un->un_persistence = 1;
11684 
11685 	/*
11686 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
11687 	 * enabled.  This will simplify the error handling for request senses
11688 	 */
11689 
11690 	if (un->un_arq_enabled && un->un_untagged_qing) {
11691 		uchar_t f_o_e;
11692 
11693 		mutex_exit(ST_MUTEX);
11694 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
11695 		    1 : 0;
11696 		mutex_enter(ST_MUTEX);
11697 
11698 		un->un_flush_on_errors = f_o_e;
11699 	} else {
11700 		un->un_flush_on_errors = 0;
11701 	}
11702 
11703 	if (un->un_flush_on_errors)
11704 		un->un_max_throttle = (uchar_t)st_max_throttle;
11705 	else
11706 		un->un_max_throttle = 1;
11707 
11708 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
11709 		un->un_max_throttle = 1;
11710 
11711 	/* this will send a marker pkt */
11712 	CLEAR_PE(un);
11713 }
11714 
11715 /*
11716  * This turns persistent errors permanently off
11717  */
11718 static void
11719 st_turn_pe_off(struct scsi_tape *un)
11720 {
11721 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
11722 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
11723 	ASSERT(mutex_owned(ST_MUTEX));
11724 
11725 	/* turn it off for good */
11726 	un->un_persistence = 0;
11727 
11728 	/* this will send a marker pkt */
11729 	CLEAR_PE(un);
11730 
11731 	/* turn off flush on error capability, if enabled */
11732 	if (un->un_flush_on_errors) {
11733 		mutex_exit(ST_MUTEX);
11734 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
11735 		mutex_enter(ST_MUTEX);
11736 	}
11737 
11738 
11739 	un->un_flush_on_errors = 0;
11740 }
11741 
11742 /*
11743  * This clear persistent errors, allowing more commands through, and also
11744  * sending a marker packet.
11745  */
11746 static void
11747 st_clear_pe(struct scsi_tape *un)
11748 {
11749 	ST_FUNC(ST_DEVINFO, st_clear_pe);
11750 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
11751 	ASSERT(mutex_owned(ST_MUTEX));
11752 
11753 	un->un_persist_errors = 0;
11754 	un->un_throttle = un->un_last_throttle = 1;
11755 	un->un_errno = 0;
11756 	st_hba_unflush(un);
11757 }
11758 
11759 /*
11760  * This will flag persistent errors, shutting everything down, if the
11761  * application had enabled persistent errors via MTIOCPERSISTENT
11762  */
11763 static void
11764 st_set_pe_flag(struct scsi_tape *un)
11765 {
11766 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
11767 	ASSERT(mutex_owned(ST_MUTEX));
11768 
11769 	if (un->un_persistence) {
11770 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
11771 		un->un_persist_errors = 1;
11772 		un->un_throttle = un->un_last_throttle = 0;
11773 	}
11774 }
11775 
11776 /*
11777  * List of commands that are allowed to be done while another host holds
11778  * the reservation.
11779  */
11780 struct {
11781 	uchar_t cmd;
11782 	uchar_t byte;	/* byte to look for data */
11783 	uint32_t mask;	/* bits that matter in the above data */
11784 } rcmds[] = {
11785 	{ SCMD_TEST_UNIT_READY, 0, 0 }, /* may fail on older drives */
11786 	{ SCMD_REQUEST_SENSE, 0, 0 },
11787 	{ SCMD_READ_BLKLIM, 0, 0 },
11788 	{ SCMD_INQUIRY, 0, 0 },
11789 	{ SCMD_RESERVE, 0, 0 },
11790 	{ SCMD_RELEASE, 0, 0 },
11791 	{ SCMD_DOORLOCK, 4, 3 },	/* allow (unlock) media access only */
11792 	{ SCMD_REPORT_DENSITIES, 0, 0 },
11793 	{ SCMD_LOG_SENSE_G1, 0, 0 },
11794 	{ SCMD_PERSISTENT_RESERVE_IN, 0, 0 },
11795 	{ SCMD_PERSISTENT_RESERVE_OUT, 0, 0 },
11796 	{ SCMD_REPORT_LUNS, 0, 0 }
11797 };
11798 
11799 static int
11800 st_do_reserve(struct scsi_tape *un)
11801 {
11802 	int rval;
11803 
11804 	ST_FUNC(ST_DEVINFO, st_do_reserve);
11805 
11806 	/*
11807 	 * Issue a Throw-Away reserve command to clear the
11808 	 * check condition.
11809 	 * If the current behaviour of reserve/release is to
11810 	 * hold reservation across opens , and if a Bus reset
11811 	 * has been issued between opens then this command
11812 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
11813 	 * In this case return an EACCES so that user knows that
11814 	 * reservation has been lost in between opens.
11815 	 * If this error is not returned and we continue with
11816 	 * successful open , then user may think position of the
11817 	 * tape is still the same but inreality we would rewind the
11818 	 * tape and continue from BOT.
11819 	 */
11820 	rval = st_reserve_release(un, ST_RESERVE);
11821 	if (rval) {
11822 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
11823 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
11824 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
11825 			un->un_errno = EACCES;
11826 			return (EACCES);
11827 		}
11828 		rval = st_reserve_release(un, ST_RESERVE);
11829 	}
11830 	if (rval == 0) {
11831 		un->un_rsvd_status |= ST_INIT_RESERVE;
11832 	}
11833 
11834 	return (rval);
11835 }
11836 
11837 static int
11838 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb)
11839 {
11840 	int i;
11841 	int rval = 0;
11842 
11843 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
11844 
11845 	/*
11846 	 * If already reserved no need to do it again.
11847 	 * Also if Reserve and Release are disabled Just return.
11848 	 */
11849 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11850 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11851 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11852 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
11853 		    st_print_scsi_cmd((uchar_t)cdb[0]));
11854 		return (0);
11855 	}
11856 
11857 	/* See if command is on the list */
11858 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11859 		if ((uchar_t)cdb[0] == rcmds[i].cmd) {
11860 			/*
11861 			 * cmd is on list.
11862 			 * if byte is zero always allowed.
11863 			 */
11864 			if (rcmds[i].byte == 0) {
11865 				return (rval);
11866 			}
11867 			if (((cdb[rcmds[i].byte]) & (rcmds[i].mask)) == 0) {
11868 				return (rval);
11869 			}
11870 			break;
11871 		}
11872 	}
11873 
11874 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11875 	    "Command %s requires reservation", st_print_scsi_cmd(cdb[0]));
11876 
11877 	rval = st_do_reserve(un);
11878 
11879 	return (rval);
11880 }
11881 
11882 static int
11883 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
11884 {
11885 	int i;
11886 	int rval = 0;
11887 
11888 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
11889 
11890 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11891 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11892 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11893 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
11894 		    st_print_scsi_cmd(cmd));
11895 		return (0);
11896 	}
11897 
11898 	/* See if command is on the list */
11899 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11900 		if (cmd == rcmds[i].cmd) {
11901 			/*
11902 			 * cmd is on list.
11903 			 * if byte is zero always allowed.
11904 			 */
11905 			if (rcmds[i].byte == 0) {
11906 				return (rval);
11907 			}
11908 			if (((rcmds[i].mask) & cnt) == 0) {
11909 				return (rval);
11910 			}
11911 			break;
11912 		}
11913 	}
11914 
11915 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11916 	    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
11917 
11918 	rval = st_do_reserve(un);
11919 
11920 	return (rval);
11921 }
11922 
11923 static int
11924 st_reserve_release(struct scsi_tape *un, int cmd)
11925 {
11926 	struct uscsi_cmd	uscsi_cmd;
11927 	struct uscsi_cmd	*com = &uscsi_cmd;
11928 	int			rval;
11929 	char			cdb[CDB_GROUP0];
11930 
11931 
11932 
11933 	ST_FUNC(ST_DEVINFO, st_reserve_release);
11934 
11935 	ASSERT(mutex_owned(ST_MUTEX));
11936 
11937 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11938 	    "st_reserve_release: %s \n",
11939 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
11940 
11941 	bzero(cdb, CDB_GROUP0);
11942 	if (cmd == ST_RELEASE) {
11943 		cdb[0] = SCMD_RELEASE;
11944 	} else {
11945 		cdb[0] = SCMD_RESERVE;
11946 	}
11947 	bzero(com, sizeof (struct uscsi_cmd));
11948 	com->uscsi_flags = USCSI_WRITE;
11949 	com->uscsi_cdb = cdb;
11950 	com->uscsi_cdblen = CDB_GROUP0;
11951 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11952 
11953 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
11954 
11955 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11956 	    "st_reserve_release: rval(1)=%d\n", rval);
11957 
11958 	if (rval) {
11959 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT) {
11960 			rval = EACCES;
11961 		}
11962 		/*
11963 		 * dynamically turn off reserve/release support
11964 		 * in case of drives which do not support
11965 		 * reserve/release command(ATAPI drives).
11966 		 */
11967 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
11968 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
11969 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
11970 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11971 				    "Tape unit does not support "
11972 				    "reserve/release \n");
11973 			}
11974 			rval = 0;
11975 		}
11976 	}
11977 	return (rval);
11978 }
11979 
11980 static int
11981 st_take_ownership(dev_t dev)
11982 {
11983 	int rval;
11984 
11985 	GET_SOFT_STATE(dev);
11986 
11987 	ST_FUNC(ST_DEVINFO, st_take_ownership);
11988 
11989 	ASSERT(mutex_owned(ST_MUTEX));
11990 
11991 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11992 	    "st_take_ownership: Entering ...\n");
11993 
11994 
11995 	rval = st_reserve_release(un, ST_RESERVE);
11996 	/*
11997 	 * XXX -> Should reset be done only if we get EACCES.
11998 	 * .
11999 	 */
12000 	if (rval) {
12001 		mutex_exit(ST_MUTEX);
12002 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
12003 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
12004 				mutex_enter(ST_MUTEX);
12005 				return (EIO);
12006 			}
12007 		}
12008 		mutex_enter(ST_MUTEX);
12009 		un->un_rsvd_status &=
12010 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12011 
12012 		mutex_exit(ST_MUTEX);
12013 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12014 		mutex_enter(ST_MUTEX);
12015 		/*
12016 		 * remove the check condition.
12017 		 */
12018 		(void) st_reserve_release(un, ST_RESERVE);
12019 		if ((rval = st_reserve_release(un, ST_RESERVE)) != 0) {
12020 			if ((st_reserve_release(un, ST_RESERVE)) != 0) {
12021 				rval = (un->un_rsvd_status &
12022 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12023 				return (rval);
12024 			}
12025 		}
12026 		/*
12027 		 * Set tape state to ST_STATE_OFFLINE , in case if
12028 		 * the user wants to continue and start using
12029 		 * the tape.
12030 		 */
12031 		un->un_state = ST_STATE_OFFLINE;
12032 		un->un_rsvd_status |= ST_INIT_RESERVE;
12033 	}
12034 	return (rval);
12035 }
12036 
12037 static int
12038 st_create_errstats(struct scsi_tape *un, int instance)
12039 {
12040 	char	kstatname[KSTAT_STRLEN];
12041 
12042 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12043 
12044 	/*
12045 	 * Create device error kstats
12046 	 */
12047 
12048 	if (un->un_errstats == (kstat_t *)0) {
12049 		(void) sprintf(kstatname, "st%d,err", instance);
12050 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12051 		    "device_error", KSTAT_TYPE_NAMED,
12052 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12053 		    KSTAT_FLAG_PERSISTENT);
12054 
12055 		if (un->un_errstats) {
12056 			struct st_errstats	*stp;
12057 
12058 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12059 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12060 			    KSTAT_DATA_ULONG);
12061 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12062 			    KSTAT_DATA_ULONG);
12063 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12064 			    KSTAT_DATA_ULONG);
12065 			kstat_named_init(&stp->st_vid, "Vendor",
12066 			    KSTAT_DATA_CHAR);
12067 			kstat_named_init(&stp->st_pid, "Product",
12068 			    KSTAT_DATA_CHAR);
12069 			kstat_named_init(&stp->st_revision, "Revision",
12070 			    KSTAT_DATA_CHAR);
12071 			kstat_named_init(&stp->st_serial, "Serial No",
12072 			    KSTAT_DATA_CHAR);
12073 			un->un_errstats->ks_private = un;
12074 			un->un_errstats->ks_update = nulldev;
12075 			kstat_install(un->un_errstats);
12076 			/*
12077 			 * Fill in the static data
12078 			 */
12079 			(void) strncpy(&stp->st_vid.value.c[0],
12080 			    ST_INQUIRY->inq_vid, 8);
12081 			/*
12082 			 * XXX:  Emulex MT-02 (and emulators) predates
12083 			 *	 SCSI-1 and has no vid & pid inquiry data.
12084 			 */
12085 			if (ST_INQUIRY->inq_len != 0) {
12086 				(void) strncpy(&stp->st_pid.value.c[0],
12087 				    ST_INQUIRY->inq_pid, 16);
12088 				(void) strncpy(&stp->st_revision.value.c[0],
12089 				    ST_INQUIRY->inq_revision, 4);
12090 				(void) strncpy(&stp->st_serial.value.c[0],
12091 				    ST_INQUIRY->inq_serial, 12);
12092 			}
12093 		}
12094 	}
12095 	return (0);
12096 }
12097 
12098 static int
12099 st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos)
12100 {
12101 	dev_t dev;
12102 	int rval;
12103 
12104 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
12105 
12106 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
12107 	ASSERT(mutex_owned(ST_MUTEX));
12108 
12109 	/* Can't restore an invalid position */
12110 	if (pos->pmode == invalid) {
12111 		return (4);
12112 	}
12113 
12114 	/*
12115 	 * Assumtions:
12116 	 *	If a position was read and is in logical position mode.
12117 	 *	If a drive supports read position it supports locate.
12118 	 *	If the read position type is not NO_POS. even though
12119 	 *	   a read position make not have been attemped yet.
12120 	 *
12121 	 *	The drive can locate to the position.
12122 	 */
12123 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
12124 		/*
12125 		 * If position mode is logical or legacy mode try
12126 		 * to locate there as it is faster.
12127 		 * If it fails try the old way.
12128 		 */
12129 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12130 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
12131 		    pos->lgclblkno);
12132 
12133 		if (st_logical_block_locate(un, pos->lgclblkno, pos->partition)
12134 		    == 0) {
12135 			/* Assume we are there copy rest of position back */
12136 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
12137 				COPY_POS(&un->un_pos, pos);
12138 			}
12139 			return (0);
12140 		}
12141 
12142 		/*
12143 		 * If logical block locate failed to restore a logical
12144 		 * position, can't recover.
12145 		 */
12146 		if (pos->pmode == logical) {
12147 			return (-1);
12148 		}
12149 	}
12150 
12151 	dev = un->un_dev;
12152 
12153 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12154 	    "Restoring tape position at fileno=%x, blkno=%x....",
12155 	    pos->fileno, pos->blkno);
12156 
12157 	/*
12158 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
12159 	 * so as not to rewind tape on RESETS: Gee, Has life ever
12160 	 * been simple in tape land ?
12161 	 */
12162 	rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
12163 	if (rval) {
12164 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12165 		"Failed to restore the last file and block position: In"
12166 		" this state, Tape will be loaded at BOT during next open");
12167 		un->un_pos.pmode = invalid;
12168 		return (rval);
12169 	}
12170 
12171 	/* If the position was as the result of back space file */
12172 	if (pos->blkno > (INF / 2)) {
12173 		/* Go one extra file forward */
12174 		pos->fileno++;
12175 		/* Figure how many blocks to back into the previous file */
12176 		pos->blkno = -(INF - pos->blkno);
12177 	}
12178 
12179 	/* Go to requested fileno */
12180 	if (pos->fileno) {
12181 		rval = st_cmd(dev, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
12182 		if (rval) {
12183 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12184 			    "Failed to restore the last file position: In this "
12185 			    " state, Tape will be loaded at BOT during next"
12186 			    " open %d", __LINE__);
12187 			un->un_pos.pmode = invalid;
12188 			pos->pmode = invalid;
12189 			return (rval);
12190 		}
12191 	}
12192 
12193 	/*
12194 	 * If backing into a file we already did an extra file forward.
12195 	 * Now we have to back over the filemark to get to the end of
12196 	 * the previous file. The blkno has been ajusted to a negative
12197 	 * value so we will get to the expected location.
12198 	 */
12199 	if (pos->blkno) {
12200 		rval = st_cmd(dev, SCMD_SPACE, Fmk(-1), SYNC_CMD);
12201 		if (rval) {
12202 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12203 			    "Failed to restore the last file position: In this "
12204 			    " state, Tape will be loaded at BOT during next"
12205 			    " open %d", __LINE__);
12206 			un->un_pos.pmode = invalid;
12207 			pos->pmode = invalid;
12208 			return (rval);
12209 		}
12210 	}
12211 
12212 	/*
12213 	 * The position mode, block and fileno should be correct,
12214 	 * This updates eof and logical position information.
12215 	 */
12216 	un->un_pos.eof = pos->eof;
12217 	un->un_pos.lgclblkno = pos->lgclblkno;
12218 
12219 	return (0);
12220 }
12221 
12222 /*
12223  * check sense key, ASC, ASCQ in order to determine if the tape needs
12224  * to be ejected
12225  */
12226 
12227 static int
12228 st_check_asc_ascq(struct scsi_tape *un)
12229 {
12230 	struct scsi_extended_sense *sensep = ST_RQSENSE;
12231 	struct tape_failure_code   *code;
12232 
12233 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
12234 
12235 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
12236 		if ((code->key  == sensep->es_key) &&
12237 		    (code->add_code  == sensep->es_add_code) &&
12238 		    (code->qual_code == sensep->es_qual_code))
12239 			return (1);
12240 	}
12241 	return (0);
12242 }
12243 
12244 /*
12245  * st_logpage_supported() sends a Log Sense command with
12246  * page code = 0 = Supported Log Pages Page to the device,
12247  * to see whether the page 'page' is supported.
12248  * Return values are:
12249  * -1 if the Log Sense command fails
12250  * 0 if page is not supported
12251  * 1 if page is supported
12252  */
12253 
12254 static int
12255 st_logpage_supported(dev_t dev, uchar_t page)
12256 {
12257 	uchar_t *sp, *sensep;
12258 	unsigned length;
12259 	struct uscsi_cmd *com;
12260 	int rval;
12261 	char cdb[CDB_GROUP1] = {
12262 		SCMD_LOG_SENSE_G1,
12263 		0,
12264 		SUPPORTED_LOG_PAGES_PAGE,
12265 		0,
12266 		0,
12267 		0,
12268 		0,
12269 		0,
12270 		(char)LOG_SENSE_LENGTH,
12271 		0
12272 	};
12273 
12274 	GET_SOFT_STATE(dev);
12275 
12276 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
12277 
12278 	ASSERT(mutex_owned(ST_MUTEX));
12279 
12280 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12281 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12282 
12283 	com->uscsi_cdb = cdb;
12284 	com->uscsi_cdblen = CDB_GROUP1;
12285 	com->uscsi_bufaddr = (caddr_t)sensep;
12286 	com->uscsi_buflen = LOG_SENSE_LENGTH;
12287 	com->uscsi_flags =
12288 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12289 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12290 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12291 	if (rval || com->uscsi_status) {
12292 		/* uscsi-command failed */
12293 		rval = -1;
12294 	} else {
12295 
12296 		sp = sensep + 3;
12297 
12298 		for (length = *sp++; length > 0; length--, sp++) {
12299 
12300 			if (*sp == page) {
12301 				rval = 1;
12302 				break;
12303 			}
12304 		}
12305 	}
12306 	kmem_free(com, sizeof (struct uscsi_cmd));
12307 	kmem_free(sensep, LOG_SENSE_LENGTH);
12308 	return (rval);
12309 }
12310 
12311 
12312 /*
12313  * st_check_clean_bit() gets the status of the tape's cleaning bit.
12314  *
12315  * If the device does support the TapeAlert log page, then the cleaning bit
12316  * information will be read from this page. Otherwise we will see if one of
12317  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
12318  * the device, which means, that we can get the cleaning bit information via
12319  * a RequestSense command.
12320  * If both methods of getting cleaning bit information are not supported
12321  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
12322  * returns with
12323  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
12324  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
12325  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
12326  * command fails, or if the amount of Request Sense data is not enough, then
12327  *  st_check_clean_bit() returns with -1.
12328  */
12329 
12330 static int
12331 st_check_clean_bit(dev_t dev)
12332 {
12333 	int rval = 0;
12334 
12335 	GET_SOFT_STATE(dev);
12336 
12337 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
12338 
12339 	ASSERT(mutex_owned(ST_MUTEX));
12340 
12341 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
12342 		return (rval);
12343 	}
12344 
12345 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12346 
12347 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
12348 		if (rval == 1) {
12349 
12350 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
12351 		}
12352 
12353 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
12354 		if (rval == 1) {
12355 
12356 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
12357 		}
12358 
12359 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12360 
12361 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
12362 		}
12363 	}
12364 
12365 	rval = 0;
12366 
12367 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
12368 
12369 		rval = st_check_sequential_clean_bit(dev);
12370 	}
12371 
12372 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
12373 
12374 		rval = st_check_alert_flags(dev);
12375 	}
12376 
12377 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
12378 
12379 		rval = st_check_sense_clean_bit(dev);
12380 	}
12381 
12382 	if (rval < 0) {
12383 		return (rval);
12384 	}
12385 
12386 	/*
12387 	 * If found a supported means to check need to clean.
12388 	 */
12389 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
12390 
12391 		/*
12392 		 * head needs to be cleaned.
12393 		 */
12394 		if (rval & MTF_TAPE_HEAD_DIRTY) {
12395 
12396 			/*
12397 			 * Print log message only first time
12398 			 * found needing cleaned.
12399 			 */
12400 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
12401 
12402 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12403 				    "Periodic head cleaning required");
12404 
12405 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
12406 			}
12407 
12408 		} else {
12409 
12410 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
12411 		}
12412 	}
12413 
12414 	return (rval);
12415 }
12416 
12417 
12418 static int
12419 st_check_sequential_clean_bit(dev_t dev)
12420 {
12421 	int rval;
12422 	int ix;
12423 	ushort_t parameter;
12424 	struct uscsi_cmd *cmd;
12425 	struct log_sequential_page *sp;
12426 	struct log_sequential_page_parameter *prm;
12427 	char cdb[CDB_GROUP1] = {
12428 		SCMD_LOG_SENSE_G1,
12429 		0,
12430 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
12431 		0,
12432 		0,
12433 		0,
12434 		0,
12435 		(char)(sizeof (struct log_sequential_page) >> 8),
12436 		(char)(sizeof (struct log_sequential_page)),
12437 		0
12438 	};
12439 
12440 	GET_SOFT_STATE(dev);
12441 
12442 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
12443 
12444 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12445 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
12446 
12447 	cmd->uscsi_flags   =
12448 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12449 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12450 	cmd->uscsi_cdb	   = cdb;
12451 	cmd->uscsi_cdblen  = CDB_GROUP1;
12452 	cmd->uscsi_bufaddr = (caddr_t)sp;
12453 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
12454 
12455 	rval = st_ioctl_cmd(dev, cmd, FKIOCTL);
12456 
12457 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
12458 
12459 		rval = -1;
12460 
12461 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
12462 
12463 		rval = -1;
12464 	}
12465 
12466 	prm = &sp->param[0];
12467 
12468 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
12469 
12470 		if (prm->log_param.length == 0) {
12471 			break;
12472 		}
12473 
12474 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
12475 		    (prm->log_param.pc_lo & 0xff));
12476 
12477 		if (parameter == SEQUENTIAL_NEED_CLN) {
12478 
12479 			rval = MTF_TAPE_CLN_SUPPORTED;
12480 			if (prm->param_value[prm->log_param.length - 1]) {
12481 
12482 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12483 				    "sequential log says head dirty\n");
12484 				rval |= MTF_TAPE_HEAD_DIRTY;
12485 			}
12486 		}
12487 		prm = (struct log_sequential_page_parameter *)
12488 		    &prm->param_value[prm->log_param.length];
12489 	}
12490 
12491 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12492 	kmem_free(sp,  sizeof (struct log_sequential_page));
12493 
12494 	return (rval);
12495 }
12496 
12497 
12498 static int
12499 st_check_alert_flags(dev_t dev)
12500 {
12501 	struct st_tape_alert *ta;
12502 	struct uscsi_cmd *com;
12503 	unsigned ix, length;
12504 	int rval;
12505 	tape_alert_flags flag;
12506 	char cdb[CDB_GROUP1] = {
12507 		SCMD_LOG_SENSE_G1,
12508 		0,
12509 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
12510 		0,
12511 		0,
12512 		0,
12513 		0,
12514 		(char)(sizeof (struct st_tape_alert) >> 8),
12515 		(char)(sizeof (struct st_tape_alert)),
12516 		0
12517 	};
12518 
12519 	GET_SOFT_STATE(dev);
12520 
12521 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
12522 
12523 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12524 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
12525 
12526 	com->uscsi_cdb = cdb;
12527 	com->uscsi_cdblen = CDB_GROUP1;
12528 	com->uscsi_bufaddr = (caddr_t)ta;
12529 	com->uscsi_buflen = sizeof (struct st_tape_alert);
12530 	com->uscsi_flags =
12531 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12532 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12533 
12534 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12535 
12536 	if (rval || com->uscsi_status || com->uscsi_resid) {
12537 
12538 		rval = -1; /* uscsi-command failed */
12539 
12540 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
12541 
12542 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12543 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
12544 		rval = -1;
12545 	}
12546 
12547 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
12548 
12549 
12550 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
12551 
12552 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12553 		    "TapeAlert length %d\n", length);
12554 	}
12555 
12556 
12557 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
12558 
12559 		/*
12560 		 * if rval is bad before the first pass don't bother
12561 		 */
12562 		if (ix == 0 && rval != 0) {
12563 
12564 			break;
12565 		}
12566 
12567 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
12568 		    ta->param[ix].log_param.pc_lo);
12569 
12570 		if ((ta->param[ix].param_value & 1) == 0) {
12571 			continue;
12572 		}
12573 		/*
12574 		 * check to see if current parameter is of interest.
12575 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
12576 		 */
12577 		if ((flag == TAF_CLEAN_NOW) ||
12578 		    (flag == TAF_CLEAN_PERIODIC) ||
12579 		    ((flag == CLEAN_FOR_ERRORS) &&
12580 		    (un->un_dp->type == ST_TYPE_STK9840))) {
12581 
12582 			rval = MTF_TAPE_CLN_SUPPORTED;
12583 
12584 
12585 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12586 			    "alert_page drive needs clean %d\n", flag);
12587 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
12588 			rval |= MTF_TAPE_HEAD_DIRTY;
12589 
12590 		} else if (flag == TAF_CLEANING_MEDIA) {
12591 
12592 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12593 			    "alert_page drive was cleaned\n");
12594 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
12595 		}
12596 
12597 	}
12598 
12599 	/*
12600 	 * Report it as dirty till we see it cleaned
12601 	 */
12602 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
12603 
12604 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12605 		    "alert_page still dirty\n");
12606 		rval |= MTF_TAPE_HEAD_DIRTY;
12607 	}
12608 
12609 	kmem_free(com, sizeof (struct uscsi_cmd));
12610 	kmem_free(ta,  sizeof (struct st_tape_alert));
12611 
12612 	return (rval);
12613 }
12614 
12615 
12616 static int
12617 st_check_sense_clean_bit(dev_t dev)
12618 {
12619 	uchar_t *sensep;
12620 	char cdb[CDB_GROUP0];
12621 	struct uscsi_cmd *com;
12622 	ushort_t byte_pos;
12623 	uchar_t bit_mask;
12624 	unsigned length;
12625 	int index;
12626 	int rval;
12627 
12628 	GET_SOFT_STATE(dev);
12629 
12630 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
12631 
12632 	/*
12633 	 * Since this tape does not support Tape Alert,
12634 	 * we now try to get the cleanbit status via
12635 	 * Request Sense.
12636 	 */
12637 
12638 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
12639 
12640 		index = 0;
12641 
12642 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
12643 
12644 		index = 1;
12645 
12646 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
12647 
12648 		index = 2;
12649 
12650 	} else {
12651 
12652 		return (-1);
12653 	}
12654 
12655 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
12656 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
12657 	length = byte_pos + 1;
12658 
12659 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12660 	sensep = kmem_zalloc(length, KM_SLEEP);
12661 
12662 	cdb[0] = SCMD_REQUEST_SENSE;
12663 	cdb[1] = 0;
12664 	cdb[2] = 0;
12665 	cdb[3] = 0;
12666 	cdb[4] = (char)length;
12667 	cdb[5] = 0;
12668 
12669 	com->uscsi_cdb = cdb;
12670 	com->uscsi_cdblen = CDB_GROUP0;
12671 	com->uscsi_bufaddr = (caddr_t)sensep;
12672 	com->uscsi_buflen = length;
12673 	com->uscsi_flags =
12674 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12675 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12676 
12677 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12678 
12679 	if (rval || com->uscsi_status || com->uscsi_resid) {
12680 
12681 		rval = -1;
12682 
12683 	} else {
12684 
12685 		rval = MTF_TAPE_CLN_SUPPORTED;
12686 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
12687 
12688 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12689 			    "sense data says head dirty\n");
12690 			rval |= MTF_TAPE_HEAD_DIRTY;
12691 		}
12692 	}
12693 
12694 	kmem_free(com, sizeof (struct uscsi_cmd));
12695 	kmem_free(sensep, length);
12696 	return (rval);
12697 }
12698 
12699 /*
12700  * st_clear_unit_attention
12701  *
12702  *  	run test unit ready's to clear out outstanding
12703  * 	unit attentions.
12704  * 	returns zero for SUCCESS or the errno from st_cmd call
12705  */
12706 static int
12707 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
12708 {
12709 	int	i    = 0;
12710 	int	rval;
12711 
12712 #ifdef DEBUG
12713 	GET_SOFT_STATE(dev_instance);
12714 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
12715 #endif
12716 
12717 	do {
12718 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
12719 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
12720 	return (rval);
12721 }
12722 
12723 static void
12724 st_calculate_timeouts(struct scsi_tape *un)
12725 {
12726 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
12727 
12728 	if (un->un_dp->non_motion_timeout == 0) {
12729 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12730 			un->un_dp->non_motion_timeout =
12731 			    st_io_time * st_long_timeout_x;
12732 		} else {
12733 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
12734 		}
12735 	}
12736 
12737 	if (un->un_dp->io_timeout == 0) {
12738 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12739 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
12740 		} else {
12741 			un->un_dp->io_timeout = (ushort_t)st_io_time;
12742 		}
12743 	}
12744 
12745 	if (un->un_dp->rewind_timeout == 0) {
12746 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12747 			un->un_dp->rewind_timeout =
12748 			    st_space_time * st_long_timeout_x;
12749 		} else {
12750 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
12751 		}
12752 	}
12753 
12754 	if (un->un_dp->space_timeout == 0) {
12755 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12756 			un->un_dp->space_timeout =
12757 			    st_space_time * st_long_timeout_x;
12758 		} else {
12759 			un->un_dp->space_timeout = (ushort_t)st_space_time;
12760 		}
12761 	}
12762 
12763 	if (un->un_dp->load_timeout == 0) {
12764 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12765 			un->un_dp->load_timeout =
12766 			    st_space_time * st_long_timeout_x;
12767 		} else {
12768 			un->un_dp->load_timeout = (ushort_t)st_space_time;
12769 		}
12770 	}
12771 
12772 	if (un->un_dp->unload_timeout == 0) {
12773 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12774 			un->un_dp->unload_timeout =
12775 			    st_space_time * st_long_timeout_x;
12776 		} else {
12777 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
12778 		}
12779 	}
12780 
12781 	if (un->un_dp->erase_timeout == 0) {
12782 		if (un->un_dp->options & ST_LONG_ERASE) {
12783 			un->un_dp->erase_timeout =
12784 			    st_space_time * st_long_space_time_x;
12785 		} else {
12786 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
12787 		}
12788 	}
12789 }
12790 
12791 
12792 static writablity
12793 st_is_not_wormable(struct scsi_tape *un)
12794 {
12795 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
12796 	return (RDWR);
12797 }
12798 
12799 static writablity
12800 st_is_hp_dat_tape_worm(struct scsi_tape *un)
12801 {
12802 	writablity wrt;
12803 
12804 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
12805 
12806 	/* Mode sense should be current */
12807 	if (un->un_mspl->media_type == 1) {
12808 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12809 		    "Drive has WORM media loaded\n");
12810 		wrt = WORM;
12811 	} else {
12812 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12813 		    "Drive has non WORM media loaded\n");
12814 		wrt = RDWR;
12815 	}
12816 	return (wrt);
12817 }
12818 
12819 #define	HP_DAT_INQUIRY 0x4A
12820 static writablity
12821 st_is_hp_dat_worm(struct scsi_tape *un)
12822 {
12823 	char *buf;
12824 	int result;
12825 	writablity wrt;
12826 
12827 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
12828 
12829 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
12830 
12831 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
12832 
12833 	if (result != 0) {
12834 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12835 		    "Read Standard Inquiry for WORM support failed");
12836 		wrt = FAILED;
12837 	} else if ((buf[40] & 1) == 0) {
12838 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12839 		    "Drive is NOT WORMable\n");
12840 		/* This drive doesn't support it so don't check again */
12841 		un->un_dp->options &= ~ST_WORMABLE;
12842 		wrt = RDWR;
12843 		un->un_wormable = st_is_not_wormable;
12844 	} else {
12845 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12846 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12847 		un->un_wormable = st_is_hp_dat_tape_worm;
12848 		wrt = un->un_wormable(un);
12849 	}
12850 
12851 	kmem_free(buf, HP_DAT_INQUIRY);
12852 
12853 	/*
12854 	 * If drive doesn't support it no point in checking further.
12855 	 */
12856 	return (wrt);
12857 }
12858 
12859 static writablity
12860 st_is_hp_lto_tape_worm(struct scsi_tape *un)
12861 {
12862 	writablity wrt;
12863 
12864 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
12865 
12866 	/* Mode sense should be current */
12867 	switch (un->un_mspl->media_type) {
12868 	case 0x00:
12869 		switch (un->un_mspl->density) {
12870 		case 0x40:
12871 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12872 			    "Drive has standard Gen I media loaded\n");
12873 			break;
12874 		case 0x42:
12875 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12876 			    "Drive has standard Gen II media loaded\n");
12877 			break;
12878 		case 0x44:
12879 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12880 			    "Drive has standard Gen III media loaded\n");
12881 			break;
12882 		case 0x46:
12883 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12884 			    "Drive has standard Gen IV media loaded\n");
12885 			break;
12886 		default:
12887 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12888 			    "Drive has standard unknown 0x%X media loaded\n",
12889 			    un->un_mspl->density);
12890 		}
12891 		wrt = RDWR;
12892 		break;
12893 	case 0x01:
12894 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12895 		    "Drive has WORM medium loaded\n");
12896 		wrt = WORM;
12897 		break;
12898 	case 0x80:
12899 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12900 		    "Drive has CD-ROM emulation medium loaded\n");
12901 		wrt = WORM;
12902 		break;
12903 	default:
12904 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12905 		    "Drive has an unexpected medium type 0x%X loaded\n",
12906 		    un->un_mspl->media_type);
12907 		wrt = RDWR;
12908 	}
12909 
12910 	return (wrt);
12911 }
12912 
12913 #define	LTO_REQ_INQUIRY 44
12914 static writablity
12915 st_is_hp_lto_worm(struct scsi_tape *un)
12916 {
12917 	char *buf;
12918 	int result;
12919 	writablity wrt;
12920 
12921 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
12922 
12923 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
12924 
12925 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
12926 
12927 	if (result != 0) {
12928 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12929 		    "Read Standard Inquiry for WORM support failed");
12930 		wrt = FAILED;
12931 	} else if ((buf[40] & 1) == 0) {
12932 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12933 		    "Drive is NOT WORMable\n");
12934 		/* This drive doesn't support it so don't check again */
12935 		un->un_dp->options &= ~ST_WORMABLE;
12936 		wrt = RDWR;
12937 		un->un_wormable = st_is_not_wormable;
12938 	} else {
12939 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12940 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12941 		un->un_wormable = st_is_hp_lto_tape_worm;
12942 		wrt = un->un_wormable(un);
12943 	}
12944 
12945 	kmem_free(buf, LTO_REQ_INQUIRY);
12946 
12947 	/*
12948 	 * If drive doesn't support it no point in checking further.
12949 	 */
12950 	return (wrt);
12951 }
12952 
12953 static writablity
12954 st_is_t10_worm_device(struct scsi_tape *un)
12955 {
12956 	writablity wrt;
12957 
12958 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
12959 
12960 	if (un->un_mspl->media_type == 0x3c) {
12961 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12962 		    "Drive has WORM media loaded\n");
12963 		wrt = WORM;
12964 	} else {
12965 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12966 		    "Drive has non WORM media loaded\n");
12967 		wrt = RDWR;
12968 	}
12969 	return (wrt);
12970 }
12971 
12972 #define	SEQ_CAP_PAGE	(char)0xb0
12973 static writablity
12974 st_is_t10_worm(struct scsi_tape *un)
12975 {
12976 	char *buf;
12977 	int result;
12978 	writablity wrt;
12979 
12980 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
12981 
12982 	buf = kmem_zalloc(6, KM_SLEEP);
12983 
12984 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
12985 
12986 	if (result != 0) {
12987 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12988 		    "Read Vitial Inquiry for Sequental Capability"
12989 		    " WORM support failed %x", result);
12990 		wrt = FAILED;
12991 	} else if ((buf[4] & 1) == 0) {
12992 		ASSERT(buf[1] == SEQ_CAP_PAGE);
12993 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12994 		    "Drive is NOT WORMable\n");
12995 		/* This drive doesn't support it so don't check again */
12996 		un->un_dp->options &= ~ST_WORMABLE;
12997 		wrt = RDWR;
12998 		un->un_wormable = st_is_not_wormable;
12999 	} else {
13000 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13001 		    "Drive supports WORM\n");
13002 		un->un_wormable = st_is_t10_worm_device;
13003 		wrt = un->un_wormable(un);
13004 	}
13005 
13006 	kmem_free(buf, 6);
13007 
13008 	return (wrt);
13009 }
13010 
13011 
13012 #define	STK_REQ_SENSE 26
13013 
13014 static writablity
13015 st_is_stk_worm(struct scsi_tape *un)
13016 {
13017 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13018 	struct scsi_extended_sense *sense;
13019 	struct uscsi_cmd *cmd;
13020 	char *buf;
13021 	int result;
13022 	writablity wrt;
13023 
13024 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13025 
13026 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13027 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13028 	sense = (struct scsi_extended_sense *)buf;
13029 
13030 	cmd->uscsi_flags = USCSI_READ;
13031 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13032 	cmd->uscsi_cdb = &cdb[0];
13033 	cmd->uscsi_bufaddr = buf;
13034 	cmd->uscsi_buflen = STK_REQ_SENSE;
13035 	cmd->uscsi_cdblen = CDB_GROUP0;
13036 	cmd->uscsi_rqlen = 0;
13037 	cmd->uscsi_rqbuf = NULL;
13038 
13039 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13040 
13041 	if (result != 0 || cmd->uscsi_status != 0) {
13042 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13043 		    "Request Sense for WORM failed");
13044 		wrt = RDWR;
13045 	} else if (sense->es_add_len + 8 < 24) {
13046 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13047 		    "Drive didn't send enough sense data for WORM byte %d\n",
13048 		    sense->es_add_len + 8);
13049 		wrt = RDWR;
13050 		un->un_wormable = st_is_not_wormable;
13051 	} else if ((buf[24]) & 0x02) {
13052 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13053 		    "Drive has WORM tape loaded\n");
13054 		wrt = WORM;
13055 		un->un_wormable = st_is_stk_worm;
13056 	} else {
13057 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13058 		    "Drive has normal tape loaded\n");
13059 		wrt = RDWR;
13060 		un->un_wormable = st_is_stk_worm;
13061 	}
13062 
13063 	kmem_free(buf, STK_REQ_SENSE);
13064 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13065 	return (wrt);
13066 }
13067 
13068 #define	DLT_INQ_SZ 44
13069 
13070 static writablity
13071 st_is_dlt_tape_worm(struct scsi_tape *un)
13072 {
13073 	caddr_t buf;
13074 	int result;
13075 	writablity wrt;
13076 
13077 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13078 
13079 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13080 
13081 	/* Read Attribute Media Type */
13082 
13083 	result = st_read_attributes(un, 0x0408, buf, 10);
13084 
13085 	/*
13086 	 * If this quantum drive is attached via an HBA that cannot
13087 	 * support thr read attributes command return error in the
13088 	 * hope that someday they will support the t10 method.
13089 	 */
13090 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
13091 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13092 		    "Read Attribute Command for WORM Media detection is not "
13093 		    "supported on the HBA that this drive is attached to.");
13094 		wrt = RDWR;
13095 		un->un_wormable = st_is_not_wormable;
13096 		goto out;
13097 	}
13098 
13099 	if (result != 0) {
13100 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13101 		    "Read Attribute Command for WORM Media returned 0x%x",
13102 		    result);
13103 		wrt = RDWR;
13104 		un->un_dp->options &= ~ST_WORMABLE;
13105 		goto out;
13106 	}
13107 
13108 	if ((uchar_t)buf[9] == 0x80) {
13109 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13110 		    "Drive media is WORM\n");
13111 		wrt = WORM;
13112 	} else {
13113 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13114 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
13115 		wrt = RDWR;
13116 	}
13117 
13118 out:
13119 	kmem_free(buf, DLT_INQ_SZ);
13120 	return (wrt);
13121 }
13122 
13123 static writablity
13124 st_is_dlt_worm(struct scsi_tape *un)
13125 {
13126 	caddr_t buf;
13127 	int result;
13128 	writablity wrt;
13129 
13130 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
13131 
13132 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13133 
13134 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
13135 
13136 	if (result != 0) {
13137 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13138 		    "Read Vendor Specific Inquiry for WORM support failed");
13139 		wrt = RDWR;
13140 		goto out;
13141 	}
13142 
13143 	if ((buf[2] & 1) == 0) {
13144 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13145 		    "Drive is not WORMable\n");
13146 		wrt = RDWR;
13147 		un->un_dp->options &= ~ST_WORMABLE;
13148 		un->un_wormable = st_is_not_wormable;
13149 		goto out;
13150 	} else {
13151 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13152 		    "Drive is WORMable\n");
13153 		un->un_wormable = st_is_dlt_tape_worm;
13154 		wrt = un->un_wormable(un);
13155 	}
13156 out:
13157 	kmem_free(buf, DLT_INQ_SZ);
13158 
13159 	return (wrt);
13160 }
13161 
13162 typedef struct {
13163 	struct modeheader_seq header;
13164 #if defined(_BIT_FIELDS_LTOH) /* X86 */
13165 	uchar_t pagecode	:6,
13166 				:2;
13167 	uchar_t page_len;
13168 	uchar_t syslogalive	:2,
13169 		device		:1,
13170 		abs		:1,
13171 		ulpbot		:1,
13172 		prth		:1,
13173 		ponej		:1,
13174 		ait		:1;
13175 	uchar_t span;
13176 
13177 	uchar_t			:6,
13178 		worm		:1,
13179 		mic		:1;
13180 	uchar_t worm_cap	:1,
13181 				:7;
13182 	uint32_t		:32;
13183 #else /* SPARC */
13184 	uchar_t			:2,
13185 		pagecode	:6;
13186 	uchar_t page_len;
13187 	uchar_t ait		:1,
13188 		device		:1,
13189 		abs		:1,
13190 		ulpbot		:1,
13191 		prth		:1,
13192 		ponej		:1,
13193 		syslogalive	:2;
13194 	uchar_t span;
13195 	uchar_t mic		:1,
13196 		worm		:1,
13197 				:6;
13198 	uchar_t			:7,
13199 		worm_cap	:1;
13200 	uint32_t		:32;
13201 #endif
13202 }ait_dev_con;
13203 
13204 #define	AIT_DEV_PAGE 0x31
13205 static writablity
13206 st_is_sony_worm(struct scsi_tape *un)
13207 {
13208 	int result;
13209 	writablity wrt;
13210 	ait_dev_con *ait_conf;
13211 
13212 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13213 
13214 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
13215 
13216 	result = st_gen_mode_sense(un, AIT_DEV_PAGE,
13217 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
13218 
13219 	if (result == 0) {
13220 
13221 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
13222 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13223 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
13224 			    ait_conf->pagecode, AIT_DEV_PAGE);
13225 			wrt = RDWR;
13226 			un->un_wormable = st_is_not_wormable;
13227 
13228 		} else if (ait_conf->worm_cap) {
13229 
13230 			un->un_wormable = st_is_sony_worm;
13231 
13232 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13233 			    "Drives is WORMable\n");
13234 			if (ait_conf->worm) {
13235 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13236 				    "Media is WORM\n");
13237 				wrt = WORM;
13238 			} else {
13239 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13240 				    "Media is not WORM\n");
13241 				wrt = RDWR;
13242 			}
13243 
13244 		} else {
13245 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13246 			    "Drives not is WORMable\n");
13247 			wrt = RDWR;
13248 			/* No further checking required */
13249 			un->un_dp->options &= ~ST_WORMABLE;
13250 		}
13251 
13252 	} else {
13253 
13254 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13255 		    "AIT device config mode sense page read command failed"
13256 		    " result = %d ", result);
13257 		wrt = FAILED;
13258 		un->un_wormable = st_is_not_wormable;
13259 	}
13260 
13261 	kmem_free(ait_conf, sizeof (ait_dev_con));
13262 	return (wrt);
13263 }
13264 
13265 static writablity
13266 st_is_drive_worm(struct scsi_tape *un)
13267 {
13268 	writablity wrt;
13269 
13270 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13271 
13272 	switch (un->un_dp->type) {
13273 	case MT_ISDLT:
13274 		wrt = st_is_dlt_worm(un);
13275 		break;
13276 
13277 	case MT_ISSTK9840:
13278 		wrt = st_is_stk_worm(un);
13279 		break;
13280 
13281 	case MT_IS8MM:
13282 	case MT_ISAIT:
13283 		wrt = st_is_sony_worm(un);
13284 		break;
13285 
13286 	case MT_LTO:
13287 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13288 			wrt = st_is_hp_lto_worm(un);
13289 		} else {
13290 			wrt = st_is_t10_worm(un);
13291 		}
13292 		break;
13293 
13294 	case MT_ISDAT:
13295 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13296 			wrt = st_is_hp_dat_worm(un);
13297 		} else {
13298 			wrt = st_is_t10_worm(un);
13299 		}
13300 		break;
13301 
13302 	default:
13303 		wrt = FAILED;
13304 		break;
13305 	}
13306 
13307 	/*
13308 	 * If any of the above failed try the t10 standard method.
13309 	 */
13310 	if (wrt == FAILED) {
13311 		wrt = st_is_t10_worm(un);
13312 	}
13313 
13314 	/*
13315 	 * Unknown method for detecting WORM media.
13316 	 */
13317 	if (wrt == FAILED) {
13318 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13319 		    "Unknown method for WORM media detection\n");
13320 		wrt = RDWR;
13321 		un->un_dp->options &= ~ST_WORMABLE;
13322 	}
13323 
13324 	return (wrt);
13325 }
13326 
13327 static int
13328 st_read_attributes(struct scsi_tape *un, uint16_t attribute, caddr_t buf,
13329     size_t size)
13330 {
13331 	char cdb[CDB_GROUP4];
13332 	int result;
13333 	struct uscsi_cmd *cmd;
13334 
13335 	ST_FUNC(ST_DEVINFO, st_read_attributes);
13336 
13337 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13338 
13339 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
13340 	cdb[1] = 0;
13341 	cdb[2] = 0;
13342 	cdb[3] = 0;
13343 	cdb[4] = 0;
13344 	cdb[5] = 0;
13345 	cdb[6] = 0;
13346 	cdb[7] = 0;
13347 	cdb[8] = (char)(attribute >> 8);
13348 	cdb[9] = (char)(attribute);
13349 	cdb[10] = (char)(size >> 24);
13350 	cdb[11] = (char)(size >> 16);
13351 	cdb[12] = (char)(size >> 8);
13352 	cdb[13] = (char)(size);
13353 	cdb[14] = 0;
13354 	cdb[15] = 0;
13355 
13356 
13357 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
13358 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13359 	cmd->uscsi_cdb = &cdb[0];
13360 	cmd->uscsi_bufaddr = (caddr_t)buf;
13361 	cmd->uscsi_buflen = size;
13362 	cmd->uscsi_cdblen = sizeof (cdb);
13363 
13364 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13365 
13366 	if (result != 0 || cmd->uscsi_status != 0) {
13367 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13368 		    "st_read_attribute failed: result %d status %d\n",
13369 		    result, cmd->uscsi_status);
13370 		if (result == 0) {
13371 			result = EIO;
13372 		}
13373 		goto exit;
13374 	}
13375 
13376 	/*
13377 	 * The attribute retured should match the attribute requested.
13378 	 */
13379 	if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
13380 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13381 		    "bad? data", buf, size);
13382 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13383 		    "st_read_attribute got wrong data back expected 0x%x"
13384 		    " got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
13385 		result = EIO;
13386 	}
13387 exit:
13388 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13389 
13390 	return (result);
13391 }
13392 
13393 static int
13394 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
13395     uchar_t page)
13396 {
13397 	char cdb[CDB_GROUP0];
13398 	struct scsi_extended_sense *sense;
13399 	struct uscsi_cmd *cmd;
13400 	int result;
13401 
13402 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
13403 
13404 	cdb[0] = SCMD_INQUIRY;
13405 	cdb[1] = page ? 1 : 0;
13406 	cdb[2] = page;
13407 	cdb[3] = 0;
13408 	cdb[4] = size;
13409 	cdb[5] = 0;
13410 
13411 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13412 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
13413 
13414 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
13415 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13416 	cmd->uscsi_cdb = &cdb[0];
13417 	cmd->uscsi_bufaddr = dest;
13418 	cmd->uscsi_buflen = size;
13419 	cmd->uscsi_cdblen = CDB_GROUP0;
13420 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
13421 	cmd->uscsi_rqbuf = (caddr_t)sense;
13422 
13423 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13424 
13425 	if (result != 0 || cmd->uscsi_status != 0) {
13426 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13427 		    "st_get_special_inquiry() failed for page %x", page);
13428 		if (result == 0) {
13429 			result = EIO;
13430 		}
13431 	}
13432 
13433 	kmem_free(sense, sizeof (struct scsi_extended_sense));
13434 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13435 
13436 	return (result);
13437 }
13438 
13439 
13440 static int
13441 st_update_block_pos(struct scsi_tape *un)
13442 {
13443 	int rval = ENOTTY;
13444 
13445 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
13446 
13447 	while (un->un_read_pos_type != NO_POS) {
13448 		rval = st_cmd(un->un_dev, SCMD_READ_POSITION, 32, SYNC_CMD);
13449 
13450 		if (rval == 0) {
13451 			rval = st_interpret_read_pos(un, un->un_read_pos_type,
13452 			    32, (caddr_t)un->un_read_pos_data);
13453 			break;
13454 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
13455 			continue;
13456 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
13457 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13458 			    "st_update_block_pos() read position cmd %x"
13459 			    " returned %x un_status = %d",
13460 			    un->un_read_pos_type, rval, un->un_status);
13461 			break;
13462 		} else {
13463 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
13464 			    "st_update_block_pos() read position cmd %x"
13465 			    " returned %x", un->un_read_pos_type, rval);
13466 		}
13467 
13468 		switch (un->un_read_pos_type) {
13469 		case SHORT_POS:
13470 			un->un_read_pos_type = NO_POS;
13471 			break;
13472 
13473 		case LONG_POS:
13474 			un->un_read_pos_type = EXT_POS;
13475 			break;
13476 
13477 		case EXT_POS:
13478 			un->un_read_pos_type = SHORT_POS;
13479 			break;
13480 
13481 		default:
13482 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13483 			    "Unexpected read position type 0x%x",
13484 			    un->un_read_pos_type);
13485 		}
13486 	}
13487 
13488 	return (rval);
13489 }
13490 
13491 static int
13492 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
13493 {
13494 	int result;
13495 	size_t d_sz;
13496 	caddr_t pos_info;
13497 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
13498 
13499 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
13500 
13501 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
13502 		return (0);
13503 	}
13504 
13505 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
13506 
13507 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13508 		    "bp_mapin_common() failed");
13509 
13510 		return (EIO);
13511 	}
13512 
13513 	pos_info = bp->b_un.b_addr;
13514 	d_sz = bp->b_bcount - bp->b_resid;
13515 
13516 #ifdef DEBUG
13517 	if ((st_debug & 0xf) > 2) {
13518 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13519 		    "st_get_read_pos() position info",
13520 		    pos_info, bp->b_bcount);
13521 	}
13522 #endif
13523 
13524 	result = st_interpret_read_pos(un, cmd->uscsi_cdb[1], d_sz, pos_info);
13525 
13526 	bp_mapout(bp);
13527 
13528 	return (result);
13529 }
13530 
13531 #if defined(_BIG_ENDIAN)
13532 
13533 #define	FIX_ENDIAN32(x)
13534 #define	FIX_ENDIAN64(x)
13535 
13536 #elif defined(_LITTLE_ENDIAN)
13537 
13538 static void
13539 st_swap32(uint32_t *val)
13540 {
13541 	uint32_t tmp;
13542 
13543 	tmp =  (*val >> 24) & 0xff;
13544 	tmp |= (*val >>  8) & 0xff00;
13545 	tmp |= (*val <<  8) & 0xff0000;
13546 	tmp |= (*val << 24) & 0xff000000;
13547 
13548 	*val = tmp;
13549 }
13550 
13551 static void
13552 st_swap64(uint64_t *val)
13553 {
13554 	uint32_t low;
13555 	uint32_t high;
13556 
13557 	low =  (uint32_t)(*val);
13558 	high = (uint32_t)(*val >> 32);
13559 
13560 	st_swap32(&low);
13561 	st_swap32(&high);
13562 
13563 	*val =  high;
13564 	*val |= ((uint64_t)low << 32);
13565 }
13566 
13567 #define	FIX_ENDIAN32(x) st_swap32(x)
13568 #define	FIX_ENDIAN64(x) st_swap64(x)
13569 #endif
13570 
13571 static int
13572 st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
13573     size_t data_sz, caddr_t responce)
13574 {
13575 	int rval = 0;
13576 
13577 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
13578 
13579 	/*
13580 	 * Look at byte 1 of cdb to see what kind of read position
13581 	 * was requested.
13582 	 */
13583 	switch (type) {
13584 
13585 	case SHORT_POS: /* Short data format */
13586 	{
13587 		tape_position_t *pos_info = (tape_position_t *)responce;
13588 		uint32_t value;
13589 
13590 		/* If reserved fields are non zero don't use the data */
13591 		if (pos_info->reserved0 || pos_info->reserved1 ||
13592 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
13593 		    pos_info->reserved3) {
13594 			rval = EIO;
13595 			break;
13596 		}
13597 		/*
13598 		 * Position is to large to use this type of read position.
13599 		 */
13600 		if (pos_info->posi_err == 1) {
13601 			rval = ERANGE;
13602 			break;
13603 		}
13604 
13605 		if (pos_info->blk_posi_unkwn == 0) {
13606 
13607 			if (un->un_pos.partition !=
13608 			    pos_info->partition_number) {
13609 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13610 				    "SHORT_POS current partition %d read %d\n",
13611 				    un->un_pos.partition,
13612 				    pos_info->partition_number);
13613 			}
13614 			un->un_pos.partition = pos_info->partition_number;
13615 			value = pos_info->host_block;
13616 			FIX_ENDIAN32(&value);
13617 
13618 			if (un->un_pos.lgclblkno != value) {
13619 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13620 				    "SHORT_POS current logical 0x%"PRIx64" read"
13621 				    " 0x%x\n", un->un_pos.lgclblkno, value);
13622 			}
13623 
13624 			un->un_pos.lgclblkno = (uint64_t)value;
13625 
13626 			if (pos_info->begin_of_part && pos_info->end_of_part) {
13627 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
13628 				    "SHORT_POS returned begin and end of"
13629 				    " partition\n");
13630 				break;
13631 			}
13632 			/* Is drive rewound */
13633 			if ((pos_info->begin_of_part == 1) &&
13634 			    (pos_info->host_block == 0)) {
13635 				un->un_pos.blkno = 0;
13636 				un->un_pos.fileno = 0;
13637 				un->un_pos.pmode = legacy;
13638 			} else if (un->un_pos.pmode == invalid) {
13639 				/* If we were lost now were found */
13640 				un->un_pos.pmode = logical;
13641 			}
13642 		} else {
13643 			un->un_pos.pmode = invalid;
13644 		}
13645 		break;
13646 	}
13647 
13648 	case LONG_POS: /* Long data format */
13649 	{
13650 		uint64_t value;
13651 		tape_position_long_t *long_pos_info =
13652 		    (tape_position_long_t *)responce;
13653 
13654 		/* If reserved fields are non zero don't use the data */
13655 		if ((long_pos_info->reserved0) ||
13656 		    (long_pos_info->reserved1) ||
13657 		    (long_pos_info->reserved2)) {
13658 			rval = EIO;
13659 			break;
13660 		}
13661 
13662 		/* Is position Valid */
13663 		if (long_pos_info->blk_posi_unkwn == 0) {
13664 			uint32_t part;
13665 
13666 			part = long_pos_info->partition;
13667 			FIX_ENDIAN32(&part);
13668 			if (un->un_pos.partition != part) {
13669 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13670 				    "LONG_POS current partition %d"
13671 				    " read %d\n", un->un_pos.partition, part);
13672 			}
13673 			un->un_pos.partition = part;
13674 			value = long_pos_info->block_number;
13675 			FIX_ENDIAN64(&value);
13676 			if (un->un_pos.lgclblkno != value) {
13677 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13678 				    "LONG_POS current logical 0x%"PRIx64
13679 				    " read 0x%"PRIx64"\n",
13680 				    un->un_pos.lgclblkno, value);
13681 			}
13682 			un->un_pos.lgclblkno = value;
13683 
13684 			if (long_pos_info->begin_of_part &&
13685 			    long_pos_info->end_of_part) {
13686 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
13687 				    "LONG_POS returned begin and end of"
13688 				    " partition\n");
13689 				break;
13690 			}
13691 			if ((long_pos_info->begin_of_part == 1) &&
13692 			    (long_pos_info->block_number == 0)) {
13693 				un->un_pos.blkno = 0;
13694 				un->un_pos.fileno = 0;
13695 				un->un_pos.pmode = legacy;
13696 			} else if (un->un_pos.pmode == invalid) {
13697 				un->un_pos.pmode = logical;
13698 			}
13699 		} else {
13700 			/*
13701 			 * If the drive doesn't know location,
13702 			 * we don't either.
13703 			 */
13704 			un->un_pos.pmode = invalid;
13705 		}
13706 
13707 		value = long_pos_info->file_number;
13708 		FIX_ENDIAN64(&value);
13709 		/* Is file position valid */
13710 		if (long_pos_info->mrk_posi_unkwn == 0) {
13711 			if (((un->un_pos.pmode == legacy) ||
13712 			    (un->un_pos.pmode == logical)) &&
13713 			    (un->un_pos.fileno != value)) {
13714 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13715 				    "LONG_POS fileno 0x%"PRIx64
13716 				    " not un_pos %x\n", value,
13717 				    un->un_pos.fileno);
13718 			} else if (un->un_pos.pmode == invalid) {
13719 				un->un_pos.pmode = logical;
13720 			}
13721 			un->un_pos.fileno = (int32_t)value;
13722 		} else {
13723 			/*
13724 			 * If the drive doesn't know its position,
13725 			 * we don't either.
13726 			 */
13727 			un->un_pos.pmode = invalid;
13728 		}
13729 		if (un->un_pos.pmode != invalid && long_pos_info->end_of_part) {
13730 			un->un_pos.eof = ST_EOT;
13731 		}
13732 
13733 		break;
13734 	}
13735 
13736 	case EXT_POS: /* Extended data format */
13737 	{
13738 		uint64_t value;
13739 		tape_position_ext_t *ext_pos_info =
13740 		    (tape_position_ext_t *)responce;
13741 
13742 		/* Make sure that there is enough data there */
13743 		if (data_sz < 16) {
13744 			break;
13745 		}
13746 
13747 		/* If reserved fields are non zero don't use the data */
13748 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
13749 			rval = EIO;
13750 			break;
13751 		}
13752 
13753 		/*
13754 		 * In the unlikely event of overflowing 64 bits of position.
13755 		 */
13756 		if (ext_pos_info->posi_err != 0) {
13757 			rval = ERANGE;
13758 			break;
13759 		}
13760 
13761 		/* Is block position information valid */
13762 		if (ext_pos_info->blk_posi_unkwn == 0) {
13763 
13764 			if (un->un_pos.partition != ext_pos_info->partition) {
13765 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13766 				    "EXT_POS current partition %d read %d\n",
13767 				    un->un_pos.partition,
13768 				    ext_pos_info->partition);
13769 			}
13770 			un->un_pos.partition = ext_pos_info->partition;
13771 
13772 			value = ext_pos_info->host_block;
13773 			FIX_ENDIAN64(&value);
13774 			if (un->un_pos.lgclblkno != value) {
13775 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13776 				    "EXT_POS current logical 0x%"PRIx64
13777 				    " read 0x%"PRIx64"\n",
13778 				    un->un_pos.lgclblkno, value);
13779 			}
13780 			un->un_pos.lgclblkno = value;
13781 			if ((ext_pos_info->begin_of_part == 1) &&
13782 			    (ext_pos_info->host_block == 0)) {
13783 				un->un_pos.blkno = 0;
13784 				un->un_pos.fileno = 0;
13785 				un->un_pos.pmode = legacy;
13786 			} else if (un->un_pos.pmode == invalid) {
13787 				un->un_pos.pmode = logical;
13788 			}
13789 		} else {
13790 			un->un_pos.pmode = invalid;
13791 		}
13792 		break;
13793 	}
13794 
13795 	default:
13796 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13797 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
13798 		rval = EIO;
13799 	}
13800 
13801 	return (rval);
13802 }
13803 
13804 static int
13805 st_logical_block_locate(struct scsi_tape *un, uint64_t lblk, uchar_t partition)
13806 {
13807 	int rval;
13808 	char cdb[CDB_GROUP4];
13809 	struct uscsi_cmd *cmd;
13810 	struct scsi_extended_sense sense;
13811 
13812 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
13813 
13814 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13815 
13816 	if (lblk <= INT32_MAX) {
13817 		cmd->uscsi_cdblen = CDB_GROUP1;
13818 		cdb[0] = SCMD_LOCATE;
13819 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13820 		cdb[2] = 0;
13821 		cdb[3] = (char)(lblk >> 24);
13822 		cdb[4] = (char)(lblk >> 16);
13823 		cdb[5] = (char)(lblk >> 8);
13824 		cdb[6] = (char)(lblk);
13825 		cdb[7] = 0;
13826 		cdb[8] = partition;
13827 		cdb[9] = 0;
13828 	} else {
13829 		/*
13830 		 * If the drive doesn't give a 64 bit read position data
13831 		 * it is unlikely it will accept 64 bit locates.
13832 		 */
13833 		if (un->un_read_pos_type != LONG_POS) {
13834 			kmem_free(cmd, sizeof (struct uscsi_cmd));
13835 			return (ERANGE);
13836 		}
13837 		cmd->uscsi_cdblen = CDB_GROUP4;
13838 		cdb[0] = (char)SCMD_LOCATE_G4;
13839 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13840 		cdb[2] = 0;
13841 		cdb[3] = partition;
13842 		cdb[4] = (char)(lblk >> 56);
13843 		cdb[5] = (char)(lblk >> 48);
13844 		cdb[6] = (char)(lblk >> 40);
13845 		cdb[7] = (char)(lblk >> 32);
13846 		cdb[8] = (char)(lblk >> 24);
13847 		cdb[9] = (char)(lblk >> 16);
13848 		cdb[10] = (char)(lblk >> 8);
13849 		cdb[11] = (char)(lblk);
13850 		cdb[12] = 0;
13851 		cdb[13] = 0;
13852 		cdb[14] = 0;
13853 		cdb[15] = 0;
13854 	}
13855 
13856 
13857 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
13858 	cmd->uscsi_rqbuf = (caddr_t)&sense;
13859 	cmd->uscsi_rqlen = sizeof (sense);
13860 	cmd->uscsi_timeout = un->un_dp->space_timeout;
13861 	cmd->uscsi_cdb = cdb;
13862 
13863 	rval = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13864 
13865 	un->un_pos.pmode = logical;
13866 	un->un_pos.eof = ST_NO_EOF;
13867 
13868 	if (lblk > INT32_MAX) {
13869 		/*
13870 		 * XXX This is a work around till we handle Descriptor format
13871 		 * sense data. Since we are sending a command where the standard
13872 		 * sense data can not correctly represent a correct residual in
13873 		 * 4 bytes.
13874 		 */
13875 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13876 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13877 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
13878 			/* Doesn't like big locate command */
13879 			un->un_status = 0;
13880 			rval = ERANGE;
13881 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
13882 			/* Aborted big locate command */
13883 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13884 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
13885 			    rval);
13886 			un->un_status = 0;
13887 			rval = EIO;
13888 		} else if (st_update_block_pos(un)) {
13889 			/* read position failed */
13890 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13891 			    "Big LOCATE and read pos: rval = %d\n", rval);
13892 			rval = EIO;
13893 		} else if (lblk > un->un_pos.lgclblkno) {
13894 			/* read position worked but position was not expected */
13895 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13896 			    "Big LOCATE and recover read less then desired 0x%"
13897 			    PRIx64"\n", un->un_pos.lgclblkno);
13898 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
13899 			un->un_status = KEY_BLANK_CHECK;
13900 			rval = ESPIPE;
13901 		} else if (lblk == un->un_pos.lgclblkno) {
13902 			/* read position was what was expected */
13903 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13904 			    "Big LOCATE and recover seems to have worked\n");
13905 			un->un_err_resid = 0;
13906 			rval = 0;
13907 		} else {
13908 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13909 			    "BIGLOCATE end up going backwards");
13910 			un->un_err_resid = lblk;
13911 			rval = EIO;
13912 		}
13913 
13914 	} else if (rval == 0) {
13915 		/* Worked as requested */
13916 		un->un_pos.lgclblkno = lblk;
13917 
13918 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
13919 	    (cmd->uscsi_resid != 0)) {
13920 		/* Got part way there but wasn't enough blocks on tape */
13921 		un->un_pos.lgclblkno = lblk - cmd->uscsi_resid;
13922 		un->un_err_resid = cmd->uscsi_resid;
13923 		un->un_status = KEY_BLANK_CHECK;
13924 		rval = ESPIPE;
13925 
13926 	} else if (st_update_block_pos(un) == 0) {
13927 		/* Got part way there but drive didn't tell what we missed by */
13928 		un->un_err_resid = lblk - un->un_pos.lgclblkno;
13929 		un->un_status = KEY_BLANK_CHECK;
13930 		rval = ESPIPE;
13931 
13932 	} else {
13933 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13934 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
13935 		    rval, cmd->uscsi_status);
13936 		un->un_err_resid = lblk;
13937 		un->un_status = KEY_ILLEGAL_REQUEST;
13938 		un->un_pos.pmode = invalid;
13939 		rval = EIO;
13940 	}
13941 
13942 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13943 
13944 	return (rval);
13945 }
13946 
13947 static int
13948 st_mtfsf_ioctl(struct scsi_tape *un, int files)
13949 {
13950 	int rval;
13951 
13952 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
13953 
13954 
13955 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13956 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13957 
13958 	/* pmode == invalid already handled */
13959 	if (un->un_pos.pmode == legacy) {
13960 		/*
13961 		 * forward space over filemark
13962 		 *
13963 		 * For ASF we allow a count of 0 on fsf which means
13964 		 * we just want to go to beginning of current file.
13965 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
13966 		 * Allow stepping over double fmk with reel
13967 		 */
13968 		if ((un->un_pos.eof >= ST_EOT) &&
13969 		    (files > 0) &&
13970 		    ((un->un_dp->options & ST_REEL) == 0)) {
13971 			/* we're at EOM */
13972 			un->un_err_resid = files;
13973 			un->un_status = KEY_BLANK_CHECK;
13974 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13975 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
13976 			return (EIO);
13977 		}
13978 
13979 		/*
13980 		 * physical tape position may not be what we've been
13981 		 * telling the user; adjust the request accordingly
13982 		 */
13983 		if (IN_EOF(un->un_pos)) {
13984 			un->un_pos.fileno++;
13985 			un->un_pos.blkno = 0;
13986 			/*
13987 			 * For positive direction case, we're now covered.
13988 			 * For zero or negative direction, we're covered
13989 			 * (almost)
13990 			 */
13991 			files--;
13992 		}
13993 
13994 	}
13995 
13996 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13997 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13998 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
13999 		return (EIO);
14000 	}
14001 
14002 
14003 	/*
14004 	 * Forward space file marks.
14005 	 * We leave ourselves at block zero
14006 	 * of the target file number.
14007 	 */
14008 	if (files < 0) {
14009 		rval = st_backward_space_files(un, -files, 0);
14010 	} else {
14011 		rval = st_forward_space_files(un, files);
14012 	}
14013 
14014 	return (rval);
14015 }
14016 
14017 static int
14018 st_forward_space_files(struct scsi_tape *un, int count)
14019 {
14020 	dev_t dev;
14021 	int rval;
14022 
14023 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
14024 
14025 	dev = un->un_dev;
14026 
14027 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14028 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
14029 
14030 	ASSERT(count >= 0);
14031 	ASSERT(un->un_pos.pmode != invalid);
14032 
14033 	/*
14034 	 * A space with a count of zero means take me to the start of file.
14035 	 */
14036 	if (count == 0) {
14037 
14038 		/* Hay look were already there */
14039 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0 &&
14040 		    un->un_pos.fileno == 0) {
14041 			un->un_err_resid = 0;
14042 			COPY_POS(&un->un_err_pos, &un->un_pos);
14043 			return (0);
14044 		}
14045 
14046 		/*
14047 		 * Well we are in the first file.
14048 		 * A rewind will get to the start.
14049 		 */
14050 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
14051 			rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
14052 
14053 		/*
14054 		 * Can we backspace to get there?
14055 		 * This should work in logical mode.
14056 		 */
14057 		} else if (un->un_dp->options & ST_BSF) {
14058 			rval = st_space_to_begining_of_file(un);
14059 
14060 		/*
14061 		 * Can't back space but current file number is known,
14062 		 * So rewind and space from the begining of the partition.
14063 		 */
14064 		} else if (un->un_pos.pmode == legacy) {
14065 			rval = st_scenic_route_to_begining_of_file(un,
14066 			    un->un_pos.fileno);
14067 
14068 		/*
14069 		 * pmode is logical and ST_BSF is not set.
14070 		 * The LONG_POS read position contains the fileno.
14071 		 * If the read position works, rewind and space.
14072 		 */
14073 		} else if (un->un_read_pos_type == LONG_POS) {
14074 			rval = st_cmd(dev, SCMD_READ_POSITION, 0, SYNC_CMD);
14075 			if (rval) {
14076 				/*
14077 				 * We didn't get the file position from the
14078 				 * read position command.
14079 				 * We are going to trust the drive to backspace
14080 				 * and then position after the filemark.
14081 				 */
14082 				rval = st_space_to_begining_of_file(un);
14083 			}
14084 			rval = st_interpret_read_pos(un, LONG_POS, 32,
14085 			    (caddr_t)un->un_read_pos_data);
14086 			if ((rval) && (un->un_pos.pmode == invalid)) {
14087 				rval = st_space_to_begining_of_file(un);
14088 			} else {
14089 				rval = st_scenic_route_to_begining_of_file(un,
14090 				    un->un_pos.fileno);
14091 			}
14092 		} else {
14093 			rval = EIO;
14094 		}
14095 		/*
14096 		 * If something didn't work we are lost
14097 		 */
14098 		if (rval != 0) {
14099 			un->un_pos.pmode = invalid;
14100 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14101 			    "st_mtioctop : EIO : fspace pmode invalid");
14102 
14103 			rval = EIO;
14104 		}
14105 
14106 	} else {
14107 		rval = st_space_fmks(dev, count);
14108 	}
14109 
14110 	if (rval != EIO && count < 0) {
14111 		/*
14112 		 * we came here with a count < 0; we now need
14113 		 * to skip back to end up before the filemark
14114 		 */
14115 		rval = st_backward_space_files(un, 1, 1);
14116 	}
14117 
14118 	return (rval);
14119 }
14120 
14121 static int
14122 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
14123 {
14124 	int rval;
14125 
14126 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
14127 
14128 	if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
14129 		rval = EIO;
14130 	} else if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
14131 		rval = EIO;
14132 	}
14133 
14134 	return (rval);
14135 }
14136 
14137 static int
14138 st_space_to_begining_of_file(struct scsi_tape *un)
14139 {
14140 	int rval;
14141 
14142 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
14143 
14144 	/*
14145 	 * Back space of the file at the begining of the file.
14146 	 */
14147 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD);
14148 	if (rval) {
14149 		rval = EIO;
14150 		return (rval);
14151 	}
14152 
14153 	/*
14154 	 * Other interesting answers might be crashed BOT which isn't bad.
14155 	 */
14156 	if (un->un_status == SUN_KEY_BOT) {
14157 		return (rval);
14158 	}
14159 
14160 	/*
14161 	 * Now we are on the BOP side of the filemark. Forward space to
14162 	 * the EOM side and we are at the begining of the file.
14163 	 */
14164 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD);
14165 	if (rval) {
14166 		rval = EIO;
14167 	}
14168 
14169 	return (rval);
14170 }
14171 
14172 static int
14173 st_mtfsr_ioctl(struct scsi_tape *un, int count)
14174 {
14175 
14176 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
14177 
14178 	/*
14179 	 * forward space to inter-record gap
14180 	 *
14181 	 */
14182 
14183 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14184 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
14185 
14186 	if (un->un_pos.pmode == legacy) {
14187 		/*
14188 		 * If were are at end of tape and count is forward.
14189 		 * Return blank check.
14190 		 */
14191 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
14192 			/* we're at EOM */
14193 			un->un_err_resid = count;
14194 			un->un_status = KEY_BLANK_CHECK;
14195 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14196 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
14197 			return (EIO);
14198 		}
14199 
14200 		/*
14201 		 * If count is zero there is nothing to do.
14202 		 */
14203 		if (count == 0) {
14204 			un->un_err_pos.fileno = un->un_pos.fileno;
14205 			un->un_err_pos.blkno = un->un_pos.blkno;
14206 			un->un_err_resid = 0;
14207 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14208 				un->un_status = SUN_KEY_EOF;
14209 			}
14210 			return (0);
14211 		}
14212 
14213 		/*
14214 		 * physical tape position may not be what we've been
14215 		 * telling the user; adjust the position accordingly
14216 		 */
14217 		if (IN_EOF(un->un_pos)) {
14218 			daddr_t blkno = un->un_pos.blkno;
14219 			int fileno = un->un_pos.fileno;
14220 
14221 			optype lastop = un->un_lastop;
14222 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
14223 			    == -1) {
14224 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14225 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
14226 				return (EIO);
14227 			}
14228 
14229 			un->un_pos.blkno = blkno;
14230 			un->un_pos.fileno = fileno;
14231 			un->un_lastop = lastop;
14232 		}
14233 	}
14234 
14235 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14236 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14237 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
14238 		return (EIO);
14239 	}
14240 
14241 	return (st_space_records(un, count));
14242 }
14243 
14244 static int
14245 st_space_records(struct scsi_tape *un, int count)
14246 {
14247 	int dblk;
14248 	int rval = 0;
14249 
14250 	ST_FUNC(ST_DEVINFO, st_space_records);
14251 
14252 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14253 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
14254 
14255 	if (un->un_pos.pmode == logical) {
14256 		rval = st_cmd(un->un_dev, SCMD_SPACE, Blk(count), SYNC_CMD);
14257 		if (rval != 0) {
14258 			rval = EIO;
14259 		}
14260 		return (rval);
14261 	}
14262 
14263 	dblk = un->un_pos.blkno + count;
14264 
14265 	/* Already there */
14266 	if (dblk == un->un_pos.blkno) {
14267 		un->un_err_resid = 0;
14268 		COPY_POS(&un->un_err_pos, &un->un_pos);
14269 		return (0);
14270 	}
14271 
14272 	/*
14273 	 * If the destination block is forward
14274 	 * or the drive will backspace records.
14275 	 */
14276 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
14277 		/*
14278 		 * If we're spacing forward, or the device can
14279 		 * backspace records, we can just use the SPACE
14280 		 * command.
14281 		 */
14282 		dblk -= un->un_pos.blkno;
14283 		if (st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
14284 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14285 			    "st_space_records:EIO:space_records can't spc");
14286 			rval = EIO;
14287 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
14288 			/*
14289 			 * check if we hit BOT/EOT
14290 			 */
14291 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
14292 				un->un_status = SUN_KEY_BOT;
14293 				un->un_pos.eof = ST_NO_EOF;
14294 			} else if (dblk < 0 &&
14295 			    un->un_pos.eof == ST_EOF_PENDING) {
14296 				int residue = un->un_err_resid;
14297 				/*
14298 				 * we skipped over a filemark
14299 				 * and need to go forward again
14300 				 */
14301 				if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1),
14302 				    SYNC_CMD)) {
14303 					ST_DEBUG2(ST_DEVINFO, st_label,
14304 					    SCSI_DEBUG, "st_space_records: EIO"
14305 					    " : can't space #2");
14306 					rval = EIO;
14307 				}
14308 				un->un_err_resid = residue;
14309 			}
14310 			if (rval == 0) {
14311 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14312 				    "st_space_records: EIO : space_rec rval"
14313 				    " == 0");
14314 				rval = EIO;
14315 			}
14316 		}
14317 	} else {
14318 		/*
14319 		 * else we rewind, space forward across filemarks to
14320 		 * the desired file, and then space records to the
14321 		 * desired block.
14322 		 */
14323 
14324 		int dfile = un->un_pos.fileno;	/* save current file */
14325 
14326 		if (dblk < 0) {
14327 			/*
14328 			 * Wups - we're backing up over a filemark
14329 			 */
14330 			if (un->un_pos.blkno != 0 &&
14331 			    (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
14332 			    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile),
14333 			    SYNC_CMD))) {
14334 				un->un_pos.pmode = invalid;
14335 			}
14336 			un->un_err_resid = -dblk;
14337 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
14338 				un->un_status = SUN_KEY_BOT;
14339 				un->un_pos.eof = ST_NO_EOF;
14340 			} else if (un->un_pos.fileno > 0) {
14341 				un->un_status = SUN_KEY_EOF;
14342 				un->un_pos.eof = ST_NO_EOF;
14343 			}
14344 			COPY_POS(&un->un_err_pos, &un->un_pos);
14345 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14346 			    "st_space_records:EIO:space_records : dblk < 0");
14347 			rval = EIO;
14348 		} else if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
14349 		    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
14350 		    st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
14351 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14352 			    "st_space_records: EIO :space_records : rewind "
14353 			    "and space failed");
14354 			un->un_pos.pmode = invalid;
14355 			rval = EIO;
14356 		}
14357 	}
14358 
14359 	return (rval);
14360 }
14361 
14362 static int
14363 st_mtbsf_ioctl(struct scsi_tape *un, int files)
14364 {
14365 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
14366 
14367 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14368 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
14369 	/*
14370 	 * backward space of file filemark (1/2" and 8mm)
14371 	 * tape position will end on the beginning of tape side
14372 	 * of the desired file mark
14373 	 */
14374 	if ((un->un_dp->options & ST_BSF) == 0) {
14375 		return (ENOTTY);
14376 	}
14377 
14378 	if (un->un_pos.pmode == legacy) {
14379 
14380 		/*
14381 		 * If a negative count (which implies a forward space op)
14382 		 * is specified, and we're at logical or physical eot,
14383 		 * bounce the request.
14384 		 */
14385 
14386 		if (un->un_pos.eof >= ST_EOT && files < 0) {
14387 			un->un_err_resid = files;
14388 			un->un_status = SUN_KEY_EOT;
14389 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14390 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
14391 			return (EIO);
14392 		}
14393 		/*
14394 		 * physical tape position may not be what we've been
14395 		 * telling the user; adjust the request accordingly
14396 		 */
14397 		if (IN_EOF(un->un_pos)) {
14398 			un->un_pos.fileno++;
14399 			un->un_pos.blkno = 0;
14400 			files++;
14401 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14402 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
14403 			    files, MTBSF);
14404 
14405 		}
14406 	}
14407 
14408 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14409 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14410 		    "st_ioctl : EIO : MTBSF : check den wfm");
14411 		return (EIO);
14412 	}
14413 
14414 	if (files <= 0) {
14415 		/*
14416 		 * for a negative count, we need to step forward
14417 		 * first and then step back again
14418 		 */
14419 		files = -files + 1;
14420 		return (st_forward_space_files(un, files));
14421 	}
14422 	return (st_backward_space_files(un, files, 1));
14423 }
14424 
14425 static int
14426 st_backward_space_files(struct scsi_tape *un, int count, int infront)
14427 {
14428 	int end_fileno;
14429 	int skip_cnt;
14430 	int rval = 0;
14431 
14432 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
14433 
14434 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14435 	    "st_backward_space_files: count=%x eof=%x\n",
14436 	    count, un->un_pos.eof);
14437 	/*
14438 	 * Backspace files (MTNBSF): infront == 0
14439 	 *
14440 	 *	For tapes that can backspace, backspace
14441 	 *	count+1 filemarks and then run forward over
14442 	 *	a filemark
14443 	 *
14444 	 *	For tapes that can't backspace,
14445 	 *		calculate desired filenumber
14446 	 *		(un->un_pos.fileno - count), rewind,
14447 	 *		and then space forward this amount
14448 	 *
14449 	 * Backspace filemarks (MTBSF) infront == 1
14450 	 *
14451 	 *	For tapes that can backspace, backspace count
14452 	 *	filemarks
14453 	 *
14454 	 *	For tapes that can't backspace, calculate
14455 	 *	desired filenumber (un->un_pos.fileno - count),
14456 	 *	add 1, rewind, space forward this amount,
14457 	 *	and mark state as ST_EOF_PENDING appropriately.
14458 	 */
14459 
14460 	if (un->un_pos.pmode == logical) {
14461 
14462 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14463 		    "st_backward_space_files: mt_op=%x count=%x"
14464 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
14465 		    un->un_pos.lgclblkno);
14466 
14467 
14468 		/* In case a drive that won't back space gets in logical mode */
14469 		if ((un->un_dp->options & ST_BSF) == 0) {
14470 			rval = EIO;
14471 			return (rval);
14472 		}
14473 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
14474 			rval = EIO;
14475 			return (rval);
14476 		}
14477 		if ((infront != 0) &&
14478 		    (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
14479 			rval = EIO;
14480 			return (rval);
14481 		}
14482 		return (rval);
14483 	}
14484 
14485 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14486 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
14487 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
14488 
14489 
14490 
14491 	/*
14492 	 * Handle the simple case of BOT
14493 	 * playing a role in these cmds.
14494 	 * We do this by calculating the
14495 	 * ending file number. If the ending
14496 	 * file is < BOT, rewind and set an
14497 	 * error and mark resid appropriately.
14498 	 * If we're backspacing a file (not a
14499 	 * filemark) and the target file is
14500 	 * the first file on the tape, just
14501 	 * rewind.
14502 	 */
14503 
14504 	/* figure expected destination of this SPACE command */
14505 	end_fileno = un->un_pos.fileno - count;
14506 
14507 	/*
14508 	 * Would the end effect of this SPACE be the same as rewinding?
14509 	 * If so just rewind instead.
14510 	 */
14511 	if ((infront != 0) && (end_fileno < 0) ||
14512 	    (infront == 0) && (end_fileno <= 0)) {
14513 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
14514 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14515 			    "st_backward_space_files: EIO : "
14516 			    "rewind in lou of BSF failed\n");
14517 			rval = EIO;
14518 		}
14519 		if (end_fileno < 0) {
14520 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14521 			    "st_backward_space_files: EIO : "
14522 			    "back space file greater then fileno\n");
14523 			rval = EIO;
14524 			un->un_err_resid = -end_fileno;
14525 			un->un_status = SUN_KEY_BOT;
14526 		}
14527 		return (rval);
14528 	}
14529 
14530 	if (un->un_dp->options & ST_BSF) {
14531 		skip_cnt = 1 - infront;
14532 		/*
14533 		 * If we are going to end up at the beginning
14534 		 * of the file, we have to space one extra file
14535 		 * first, and then space forward later.
14536 		 */
14537 		end_fileno = -(count + skip_cnt);
14538 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
14539 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
14540 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
14541 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14542 			    "st_backward_space_files:EIO:back space fm failed");
14543 			rval = EIO;
14544 		}
14545 	} else {
14546 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
14547 			rval = EIO;
14548 		} else {
14549 			skip_cnt = end_fileno + infront;
14550 		}
14551 	}
14552 
14553 	/*
14554 	 * If we have to space forward, do so...
14555 	 */
14556 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
14557 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
14558 
14559 	if (rval == 0 && skip_cnt) {
14560 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
14561 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14562 			    "st_backward_space_files:EIO:space fm skip count");
14563 			rval = EIO;
14564 		} else if (infront) {
14565 			/*
14566 			 * If we had to space forward, and we're
14567 			 * not a tape that can backspace, mark state
14568 			 * as if we'd just seen a filemark during a
14569 			 * a read.
14570 			 */
14571 			if ((un->un_dp->options & ST_BSF) == 0) {
14572 				un->un_pos.eof = ST_EOF_PENDING;
14573 				un->un_pos.fileno -= 1;
14574 				un->un_pos.blkno = INF;
14575 			}
14576 		}
14577 	}
14578 
14579 	if (rval != 0) {
14580 		un->un_pos.pmode = invalid;
14581 	}
14582 
14583 	return (rval);
14584 }
14585 
14586 static int
14587 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
14588 {
14589 	int rval;
14590 
14591 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
14592 
14593 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14594 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
14595 
14596 	if (un->un_pos.pmode == legacy) {
14597 		/*
14598 		 * backward space file to beginning of file
14599 		 *
14600 		 * If a negative count (which implies a forward space op)
14601 		 * is specified, and we're at logical or physical eot,
14602 		 * bounce the request.
14603 		 */
14604 
14605 		if (un->un_pos.eof >= ST_EOT && count < 0) {
14606 			un->un_err_resid = count;
14607 			un->un_status = SUN_KEY_EOT;
14608 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14609 			    "st_ioctl : EIO : > EOT and count < 0");
14610 			return (EIO);
14611 		}
14612 		/*
14613 		 * physical tape position may not be what we've been
14614 		 * telling the user; adjust the request accordingly
14615 		 */
14616 		if (IN_EOF(un->un_pos)) {
14617 			un->un_pos.fileno++;
14618 			un->un_pos.blkno = 0;
14619 			count++;
14620 		}
14621 	}
14622 
14623 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14624 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14625 		    "st_ioctl : EIO : MTNBSF check den and wfm");
14626 		return (EIO);
14627 	}
14628 
14629 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14630 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
14631 
14632 	if (count <= 0) {
14633 		rval = st_forward_space_files(un, -count);
14634 	} else {
14635 		rval = st_backward_space_files(un, count, 0);
14636 	}
14637 	return (rval);
14638 }
14639 
14640 static int
14641 st_mtbsr_ioctl(struct scsi_tape *un, int num)
14642 {
14643 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
14644 
14645 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14646 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
14647 
14648 	if (un->un_pos.pmode == legacy) {
14649 		/*
14650 		 * backward space into inter-record gap
14651 		 *
14652 		 * If a negative count (which implies a forward space op)
14653 		 * is specified, and we're at logical or physical eot,
14654 		 * bounce the request.
14655 		 */
14656 		if (un->un_pos.eof >= ST_EOT && num < 0) {
14657 			un->un_err_resid = num;
14658 			un->un_status = SUN_KEY_EOT;
14659 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14660 			    "st_ioctl : EIO : MTBSR > EOT");
14661 			return (EIO);
14662 		}
14663 
14664 		if (num == 0) {
14665 			COPY_POS(&un->un_err_pos, &un->un_pos);
14666 			un->un_err_resid = 0;
14667 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14668 				un->un_status = SUN_KEY_EOF;
14669 			}
14670 			return (0);
14671 		}
14672 
14673 		/*
14674 		 * physical tape position may not be what we've been
14675 		 * telling the user; adjust the position accordingly.
14676 		 * bsr can not skip filemarks and continue to skip records
14677 		 * therefore if we are logically before the filemark but
14678 		 * physically at the EOT side of the filemark, we need to step
14679 		 * back; this allows fsr N where N > number of blocks in file
14680 		 * followed by bsr 1 to position at the beginning of last block
14681 		 */
14682 		if (IN_EOF(un->un_pos)) {
14683 			tapepos_t save;
14684 			optype lastop = un->un_lastop;
14685 
14686 			COPY_POS(&save, &un->un_pos);
14687 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
14688 			    == -1) {
14689 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14690 				    "st_write_fm : EIO : MTBSR can't space");
14691 				return (EIO);
14692 			}
14693 
14694 			COPY_POS(&un->un_pos, &save);
14695 			un->un_lastop = lastop;
14696 		}
14697 	}
14698 
14699 	un->un_pos.eof = ST_NO_EOF;
14700 
14701 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14702 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14703 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
14704 		return (EIO);
14705 	}
14706 
14707 	num = -num;
14708 	return (st_space_records(un, num));
14709 }
14710 
14711 static int
14712 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
14713 {
14714 	int rval;
14715 
14716 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
14717 
14718 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
14719 	if (rval == 0) {
14720 		un->un_pos.pmode = logical;
14721 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14722 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14723 		/*
14724 		 * Drive says invalid field in cdb.
14725 		 * Doesn't like space multiple. Position isn't lost.
14726 		 */
14727 		un->un_err_resid = cnt;
14728 		un->un_status = 0;
14729 		rval = ENOTTY;
14730 	} else {
14731 		un->un_err_resid = cnt;
14732 		un->un_pos.pmode = invalid;
14733 	}
14734 	return (rval);
14735 }
14736 
14737 static int
14738 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
14739 {
14740 	int rval;
14741 
14742 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
14743 
14744 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
14745 	if (rval == 0) {
14746 		un->un_pos.pmode = logical;
14747 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14748 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14749 		/*
14750 		 * Drive says invalid field in cdb.
14751 		 * Doesn't like space multiple. Position isn't lost.
14752 		 */
14753 		un->un_err_resid = cnt;
14754 		un->un_status = 0;
14755 		rval = ENOTTY;
14756 	} else {
14757 		un->un_err_resid = cnt;
14758 		un->un_pos.pmode = invalid;
14759 	}
14760 	return (rval);
14761 }
14762 
14763 #ifdef	__x86
14764 
14765 /*
14766  * release contig_mem and wake up waiting thread, if any
14767  */
14768 static void
14769 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
14770 {
14771 	mutex_enter(ST_MUTEX);
14772 
14773 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
14774 
14775 	cp->cm_next = un->un_contig_mem;
14776 	un->un_contig_mem = cp;
14777 	un->un_contig_mem_available_num++;
14778 	cv_broadcast(&un->un_contig_mem_cv);
14779 
14780 	mutex_exit(ST_MUTEX);
14781 }
14782 
14783 /*
14784  * St_get_contig_mem will return a contig_mem if there is one available
14785  * in current system. Otherwise, it will try to alloc one, if the total
14786  * number of contig_mem is within st_max_contig_mem_num.
14787  * It will sleep, if allowed by caller or return NULL, if no contig_mem
14788  * is available for now.
14789  */
14790 static struct contig_mem *
14791 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
14792 {
14793 	size_t rlen;
14794 	struct contig_mem *cp = NULL;
14795 	ddi_acc_handle_t acc_hdl;
14796 	caddr_t addr;
14797 	int big_enough = 0;
14798 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
14799 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
14800 
14801 	/* Try to get one available contig_mem */
14802 	mutex_enter(ST_MUTEX);
14803 
14804 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
14805 
14806 	if (un->un_contig_mem_available_num > 0) {
14807 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14808 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
14809 		/*
14810 		 * we failed to get one. we're going to
14811 		 * alloc one more contig_mem for this I/O
14812 		 */
14813 		mutex_exit(ST_MUTEX);
14814 		cp = (struct contig_mem *)kmem_zalloc(
14815 		    sizeof (struct contig_mem) + biosize(),
14816 		    alloc_flags);
14817 		if (cp == NULL) {
14818 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14819 			    "alloc contig_mem failure\n");
14820 			return (NULL); /* cannot get one */
14821 		}
14822 		cp->cm_bp = (struct buf *)
14823 		    (((caddr_t)cp) + sizeof (struct contig_mem));
14824 		bioinit(cp->cm_bp);
14825 		mutex_enter(ST_MUTEX);
14826 		un->un_contig_mem_total_num++; /* one more available */
14827 	} else {
14828 		/*
14829 		 * we failed to get one and we're NOT allowed to
14830 		 * alloc more contig_mem
14831 		 */
14832 		if (alloc_flags == KM_SLEEP) {
14833 			while (un->un_contig_mem_available_num <= 0) {
14834 				cv_wait(&un->un_contig_mem_cv,
14835 				    ST_MUTEX);
14836 			}
14837 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14838 		} else {
14839 			mutex_exit(ST_MUTEX);
14840 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14841 			    "alloc contig_mem failure\n");
14842 			return (NULL); /* cannot get one */
14843 		}
14844 	}
14845 	mutex_exit(ST_MUTEX);
14846 
14847 	/* We need to check if this block of mem is big enough for this I/O */
14848 	if (cp->cm_len < len) {
14849 		/* not big enough, need to alloc a new one */
14850 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
14851 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
14852 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
14853 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14854 			    "alloc contig_mem failure: not enough mem\n");
14855 			st_release_contig_mem(un, cp);
14856 			cp = NULL;
14857 		} else {
14858 			if (cp->cm_addr) {
14859 				/* release previous one before attach new one */
14860 				ddi_dma_mem_free(&cp->cm_acc_hdl);
14861 			}
14862 			mutex_enter(ST_MUTEX);
14863 			un->un_max_contig_mem_len =
14864 			    un->un_max_contig_mem_len >= len ?
14865 			    un->un_max_contig_mem_len : len;
14866 			mutex_exit(ST_MUTEX);
14867 
14868 			/* attach new mem to this cp */
14869 			cp->cm_addr = addr;
14870 			cp->cm_acc_hdl = acc_hdl;
14871 			cp->cm_len = len;
14872 
14873 			goto alloc_ok; /* get one usable cp */
14874 		}
14875 	} else {
14876 		goto alloc_ok; /* get one usable cp */
14877 	}
14878 
14879 	/* cannot find/alloc a usable cp, when we get here */
14880 
14881 	mutex_enter(ST_MUTEX);
14882 	if ((un->un_max_contig_mem_len < len) ||
14883 	    (alloc_flags != KM_SLEEP)) {
14884 		mutex_exit(ST_MUTEX);
14885 		return (NULL);
14886 	}
14887 
14888 	/*
14889 	 * we're allowed to sleep, and there is one big enough
14890 	 * contig mem in the system, which is currently in use,
14891 	 * wait for it...
14892 	 */
14893 	big_enough = 1;
14894 	do {
14895 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
14896 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14897 	} while (cp == NULL);
14898 	mutex_exit(ST_MUTEX);
14899 
14900 	/* we get the big enough contig mem, finally */
14901 
14902 alloc_ok:
14903 	/* init bp attached to this cp */
14904 	bioreset(cp->cm_bp);
14905 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
14906 	cp->cm_bp->b_private = (void *)cp;
14907 
14908 	return (cp);
14909 }
14910 
14911 /*
14912  * this is the biodone func for the bp used in big block I/O
14913  */
14914 static int
14915 st_bigblk_xfer_done(struct buf *bp)
14916 {
14917 	struct contig_mem *cp;
14918 	struct buf *orig_bp;
14919 	int ioerr;
14920 	struct scsi_tape *un;
14921 
14922 	/* sanity check */
14923 	if (bp == NULL) {
14924 		return (DDI_FAILURE);
14925 	}
14926 
14927 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14928 	if (un == NULL) {
14929 		return (DDI_FAILURE);
14930 	}
14931 
14932 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
14933 
14934 	cp = (struct contig_mem *)bp->b_private;
14935 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
14936 	cp->cm_bp = bp;
14937 
14938 	/* special handling for special I/O */
14939 	if (cp->cm_use_sbuf) {
14940 #ifndef __lock_lint
14941 		ASSERT(un->un_sbuf_busy);
14942 #endif
14943 		un->un_sbufp = orig_bp;
14944 		cp->cm_use_sbuf = 0;
14945 	}
14946 
14947 	orig_bp->b_resid = bp->b_resid;
14948 	ioerr = geterror(bp);
14949 	if (ioerr != 0) {
14950 		bioerror(orig_bp, ioerr);
14951 	} else if (orig_bp->b_flags & B_READ) {
14952 		/* copy data back to original bp */
14953 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
14954 		    bp->b_bcount - bp->b_resid);
14955 	}
14956 
14957 	st_release_contig_mem(un, cp);
14958 
14959 	biodone(orig_bp);
14960 
14961 	return (DDI_SUCCESS);
14962 }
14963 
14964 /*
14965  * We use this func to replace original bp that may not be able to do I/O
14966  * in big block size with one that can
14967  */
14968 static struct buf *
14969 st_get_bigblk_bp(struct buf *bp)
14970 {
14971 	struct contig_mem *cp;
14972 	struct scsi_tape *un;
14973 	struct buf *cont_bp;
14974 
14975 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14976 	if (un == NULL) {
14977 		return (bp);
14978 	}
14979 
14980 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
14981 
14982 	/* try to get one contig_mem */
14983 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
14984 	if (!cp) {
14985 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
14986 		    "Cannot alloc contig buf for I/O for %lu blk size",
14987 		    bp->b_bcount);
14988 		return (bp);
14989 	}
14990 	cont_bp = cp->cm_bp;
14991 	cp->cm_bp = bp;
14992 
14993 	/* make sure that we "are" using un_sbufp for special I/O */
14994 	if (bp == un->un_sbufp) {
14995 #ifndef __lock_lint
14996 		ASSERT(un->un_sbuf_busy);
14997 #endif
14998 		un->un_sbufp = cont_bp;
14999 		cp->cm_use_sbuf = 1;
15000 	}
15001 
15002 	/* clone bp */
15003 	cont_bp->b_bcount = bp->b_bcount;
15004 	cont_bp->b_resid = bp->b_resid;
15005 	cont_bp->b_iodone = st_bigblk_xfer_done;
15006 	cont_bp->b_file = bp->b_file;
15007 	cont_bp->b_offset = bp->b_offset;
15008 	cont_bp->b_dip = bp->b_dip;
15009 	cont_bp->b_error = 0;
15010 	cont_bp->b_proc = NULL;
15011 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
15012 	cont_bp->b_shadow = NULL;
15013 	cont_bp->b_pages = NULL;
15014 	cont_bp->b_edev = bp->b_edev;
15015 	cont_bp->b_dev = bp->b_dev;
15016 	cont_bp->b_lblkno = bp->b_lblkno;
15017 	cont_bp->b_forw = bp->b_forw;
15018 	cont_bp->b_back = bp->b_back;
15019 	cont_bp->av_forw = bp->av_forw;
15020 	cont_bp->av_back = bp->av_back;
15021 	cont_bp->b_bufsize = bp->b_bufsize;
15022 
15023 	/* get data in original bp */
15024 	if (bp->b_flags & B_WRITE) {
15025 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
15026 	}
15027 
15028 	return (cont_bp);
15029 }
15030 #else
15031 #ifdef __lock_lint
15032 static int
15033 st_bigblk_xfer_done(struct buf *bp)
15034 {
15035 	return (0);
15036 }
15037 #endif
15038 #endif
15039 
15040 static const char *eof_status[] =
15041 {
15042 	"NO_EOF",
15043 	"EOF_PENDING",
15044 	"EOF",
15045 	"EOT_PENDING",
15046 	"EOT",
15047 	"EOM",
15048 	"AFTER_EOM"
15049 };
15050 static const char *mode[] = {
15051 	"invalid",
15052 	"legacy",
15053 	"logical"
15054 };
15055 
15056 static void
15057 st_print_position(struct scsi_tape *un, const char *comment, tapepos_t *pos)
15058 {
15059 	ST_FUNC(ST_DEVINFO, st_print_position);
15060 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
15061 	    "%s Position data:\n", comment);
15062 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
15063 	    "Positioning mode = %s", mode[pos->pmode]);
15064 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
15065 	    "End Of File/Tape = %s", eof_status[pos->eof]);
15066 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
15067 	    "File Number      = 0x%x", pos->fileno);
15068 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
15069 	    "Block Number     = 0x%x", pos->blkno);
15070 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
15071 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
15072 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
15073 	    "Partition Number = 0x%x", pos->partition);
15074 }
15075