xref: /titanic_51/usr/src/uts/common/io/scsi/targets/st.c (revision 911106dfb16696472af8c1b7b4c554a829354fa8)
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 
1693 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1694 	/*
1695 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1696 	 *	 no vid & pid inquiry data.  So, we provide one.
1697 	 */
1698 	if (ST_INQUIRY->inq_len == 0 ||
1699 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1700 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1701 	}
1702 
1703 	un->un_dp_size = sizeof (struct st_drivetype);
1704 	dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1705 	un->un_dp = dp;
1706 
1707 	un->un_dp->non_motion_timeout = st_io_time;
1708 	/*
1709 	 * Loop through the configuration methods till one works.
1710 	 */
1711 	for (config_funct = &config_functs[0]; ; config_funct++) {
1712 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1713 			break;
1714 		}
1715 	}
1716 
1717 	/*
1718 	 * If we didn't just make up this configuration and
1719 	 * all the density codes are the same..
1720 	 * Set Auto Density over ride.
1721 	 */
1722 	if (*config_funct != st_get_default_conf) {
1723 		/*
1724 		 * If this device is one that is configured and all
1725 		 * densities are the same, This saves doing gets and set
1726 		 * that yield nothing.
1727 		 */
1728 		if ((dp->densities[0]) == (dp->densities[1]) &&
1729 		    (dp->densities[0]) == (dp->densities[2]) &&
1730 		    (dp->densities[0]) == (dp->densities[3])) {
1731 
1732 			dp->options |= ST_AUTODEN_OVERRIDE;
1733 		}
1734 	}
1735 
1736 
1737 	/*
1738 	 * Store tape drive characteristics.
1739 	 */
1740 	un->un_status = 0;
1741 	un->un_attached = 1;
1742 	un->un_init_options = dp->options;
1743 
1744 	/* setup operation time-outs based on options */
1745 	st_calculate_timeouts(un);
1746 
1747 	/* make sure if we are supposed to be variable, make it variable */
1748 	if (dp->options & ST_VARIABLE) {
1749 		dp->bsize = 0;
1750 	}
1751 
1752 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1753 }
1754 
1755 
1756 typedef struct {
1757 	int mask;
1758 	int bottom;
1759 	int top;
1760 	char *name;
1761 } conf_limit;
1762 
1763 static const conf_limit conf_limits[] = {
1764 
1765 	-1,		1,		2,		"conf version",
1766 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1767 	-1,		0,		0xffffff,	"block size",
1768 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1769 	-1,		0,		4,		"number of densities",
1770 	-1,		0,		UINT8_MAX,	"density code",
1771 	-1,		0,		3,		"default density",
1772 	-1,		0,		UINT16_MAX,	"non motion timeout",
1773 	-1,		0,		UINT16_MAX,	"I/O timeout",
1774 	-1,		0,		UINT16_MAX,	"space timeout",
1775 	-1,		0,		UINT16_MAX,	"load timeout",
1776 	-1,		0,		UINT16_MAX,	"unload timeout",
1777 	-1,		0,		UINT16_MAX,	"erase timeout",
1778 	0,		0,		0,		NULL
1779 };
1780 
1781 static int
1782 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1783     const char *conf_name)
1784 {
1785 	int dens;
1786 	int ndens;
1787 	int value;
1788 	int type;
1789 	int count;
1790 	const conf_limit *limit = &conf_limits[0];
1791 
1792 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1793 
1794 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1795 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1796 
1797 	count = list_len;
1798 	type = *list;
1799 	for (;  count && limit->name; count--, list++, limit++) {
1800 
1801 		value = *list;
1802 		if (value & ~limit->mask) {
1803 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1804 			    "%s %s value invalid bits set: 0x%X\n",
1805 			    conf_name, limit->name, value & ~limit->mask);
1806 			*list &= limit->mask;
1807 		} else if (value < limit->bottom) {
1808 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1809 			    "%s %s value too low: value = %d limit %d\n",
1810 			    conf_name, limit->name, value, limit->bottom);
1811 		} else if (value > limit->top) {
1812 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1813 			    "%s %s value too high: value = %d limit %d\n",
1814 			    conf_name, limit->name, value, limit->top);
1815 		} else {
1816 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1817 			    "%s %s value = 0x%X\n",
1818 			    conf_name, limit->name, value);
1819 		}
1820 
1821 		/* If not the number of densities continue */
1822 		if (limit != &conf_limits[4]) {
1823 			continue;
1824 		}
1825 
1826 		/* If number of densities is not in range can't use config */
1827 		if (value < limit->bottom || value > limit->top) {
1828 			return (-1);
1829 		}
1830 
1831 		ndens = min(value, NDENSITIES);
1832 		if ((type == 1) && (list_len - ndens) != 6) {
1833 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1834 			    "%s conf version 1 with %d densities has %d items"
1835 			    " should have %d",
1836 			    conf_name, ndens, list_len, 6 + ndens);
1837 		} else if ((type == 2) && (list_len - ndens) != 13) {
1838 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1839 			    "%s conf version 2 with %d densities has %d items"
1840 			    " should have %d",
1841 			    conf_name, ndens, list_len, 13 + ndens);
1842 		}
1843 
1844 		limit++;
1845 		for (dens = 0; dens < ndens && count; dens++) {
1846 			count--;
1847 			list++;
1848 			value = *list;
1849 			if (value < limit->bottom) {
1850 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1851 				    "%s density[%d] value too low: value ="
1852 				    " 0x%X limit 0x%X\n",
1853 				    conf_name, dens, value, limit->bottom);
1854 			} else if (value > limit->top) {
1855 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1856 				    "%s density[%d] value too high: value ="
1857 				    " 0x%X limit 0x%X\n",
1858 				    conf_name, dens, value, limit->top);
1859 			} else {
1860 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1861 				    "%s density[%d] value = 0x%X\n",
1862 				    conf_name, dens, value);
1863 			}
1864 		}
1865 	}
1866 
1867 	return (0);
1868 }
1869 
1870 static int
1871 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1872     struct st_drivetype *dp)
1873 {
1874 	caddr_t config_list = NULL;
1875 	caddr_t data_list = NULL;
1876 	int	*data_ptr;
1877 	caddr_t vidptr, prettyptr, datanameptr;
1878 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1879 	int config_list_len, data_list_len, len, i;
1880 	int version;
1881 	int found = 0;
1882 
1883 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
1884 
1885 	/*
1886 	 * Determine type of tape controller. Type is determined by
1887 	 * checking the vendor ids of the earlier inquiry command and
1888 	 * comparing those with vids in tape-config-list defined in st.conf
1889 	 */
1890 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1891 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1892 	    != DDI_PROP_SUCCESS) {
1893 		return (found);
1894 	}
1895 
1896 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1897 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1898 
1899 	/*
1900 	 * Compare vids in each triplet - if it matches, get value for
1901 	 * data_name and contruct a st_drivetype struct
1902 	 * tripletlen is not set yet!
1903 	 */
1904 	for (len = config_list_len, vidptr = config_list;
1905 	    len > 0;
1906 	    vidptr += tripletlen, len -= tripletlen) {
1907 
1908 		vidlen = strlen(vidptr);
1909 		prettyptr = vidptr + vidlen + 1;
1910 		prettylen = strlen(prettyptr);
1911 		datanameptr = prettyptr + prettylen + 1;
1912 		datanamelen = strlen(datanameptr);
1913 		tripletlen = vidlen + prettylen + datanamelen + 3;
1914 
1915 		if (vidlen == 0) {
1916 			continue;
1917 		}
1918 
1919 		/*
1920 		 * If inquiry vid dosen't match this triplets vid,
1921 		 * try the next.
1922 		 */
1923 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1924 			continue;
1925 		}
1926 
1927 		/*
1928 		 * if prettylen is zero then use the vid string
1929 		 */
1930 		if (prettylen == 0) {
1931 			prettyptr = vidptr;
1932 			prettylen = vidlen;
1933 		}
1934 
1935 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1936 		    "vid = %s, pretty=%s, dataname = %s\n",
1937 		    vidptr, prettyptr, datanameptr);
1938 
1939 		/*
1940 		 * get the data list
1941 		 */
1942 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1943 		    datanameptr, (caddr_t)&data_list,
1944 		    &data_list_len) != DDI_PROP_SUCCESS) {
1945 			/*
1946 			 * Error in getting property value
1947 			 * print warning!
1948 			 */
1949 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1950 			    "data property (%s) has no value\n",
1951 			    datanameptr);
1952 			continue;
1953 		}
1954 
1955 		/*
1956 		 * now initialize the st_drivetype struct
1957 		 */
1958 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1959 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1960 		(void) strncpy(dp->vid, vidptr, dp->length);
1961 		data_ptr = (int *)data_list;
1962 		/*
1963 		 * check if data is enough for version, type,
1964 		 * bsize, options, # of densities, density1,
1965 		 * density2, ..., default_density
1966 		 */
1967 		if ((data_list_len < 5 * sizeof (int)) ||
1968 		    (data_list_len < 6 * sizeof (int) +
1969 		    *(data_ptr + 4) * sizeof (int))) {
1970 			/*
1971 			 * print warning and skip to next triplet.
1972 			 */
1973 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1974 			    "data property (%s) incomplete\n",
1975 			    datanameptr);
1976 			kmem_free(data_list, data_list_len);
1977 			continue;
1978 		}
1979 
1980 		if (st_validate_conf_data(un, data_ptr,
1981 		    data_list_len / sizeof (int), datanameptr)) {
1982 			kmem_free(data_list, data_list_len);
1983 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1984 			    "data property (%s) rejected\n",
1985 			    datanameptr);
1986 			continue;
1987 		}
1988 
1989 		/*
1990 		 * check version
1991 		 */
1992 		version = *data_ptr++;
1993 		if (version != 1 && version != 2) {
1994 			/* print warning but accept it */
1995 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1996 			    "Version # for data property (%s) "
1997 			    "not set to 1 or 2\n", datanameptr);
1998 		}
1999 
2000 		dp->type    = *data_ptr++;
2001 		dp->bsize   = *data_ptr++;
2002 		dp->options = *data_ptr++;
2003 		dp->options |= ST_DYNAMIC;
2004 		len = *data_ptr++;
2005 		for (i = 0; i < NDENSITIES; i++) {
2006 			if (i < len) {
2007 				dp->densities[i] = *data_ptr++;
2008 			}
2009 		}
2010 		dp->default_density = *data_ptr << 3;
2011 		if (version == 2 &&
2012 		    data_list_len >= (13 + len) * sizeof (int)) {
2013 			data_ptr++;
2014 			dp->non_motion_timeout	= *data_ptr++;
2015 			dp->io_timeout		= *data_ptr++;
2016 			dp->rewind_timeout	= *data_ptr++;
2017 			dp->space_timeout	= *data_ptr++;
2018 			dp->load_timeout	= *data_ptr++;
2019 			dp->unload_timeout	= *data_ptr++;
2020 			dp->erase_timeout	= *data_ptr++;
2021 		}
2022 		kmem_free(data_list, data_list_len);
2023 		found = 1;
2024 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2025 		    "found in st.conf: vid = %s, pretty=%s\n",
2026 		    dp->vid, dp->name);
2027 		break;
2028 	}
2029 
2030 	/*
2031 	 * free up the memory allocated by ddi_getlongprop
2032 	 */
2033 	if (config_list) {
2034 		kmem_free(config_list, config_list_len);
2035 	}
2036 	return (found);
2037 }
2038 
2039 static int
2040 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2041     struct st_drivetype *dp)
2042 {
2043 	int i;
2044 
2045 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2046 	/*
2047 	 * Determine type of tape controller.  Type is determined by
2048 	 * checking the result of the earlier inquiry command and
2049 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2050 	 */
2051 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2052 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2053 
2054 	for (i = 0; i < st_ndrivetypes; i++) {
2055 		if (st_drivetypes[i].length == 0) {
2056 			continue;
2057 		}
2058 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2059 		    st_drivetypes[i].length)) {
2060 			continue;
2061 		}
2062 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2063 		return (1);
2064 	}
2065 	return (0);
2066 }
2067 
2068 static int
2069 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2070     struct st_drivetype *dp)
2071 {
2072 	int bsize;
2073 	ulong_t maxbsize;
2074 	caddr_t buf;
2075 	struct st_drivetype *tem_dp;
2076 	struct read_blklim *blklim;
2077 	int rval;
2078 	int i;
2079 
2080 	ST_FUNC(ST_DEVINFO, st_get_conf_from_type_drive);
2081 
2082 	/*
2083 	 * Determine the type of tape controller. Type is determined by
2084 	 * sending SCSI commands to tape drive and deriving the type from
2085 	 * the returned data.
2086 	 */
2087 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2088 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2089 
2090 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2091 
2092 	/*
2093 	 * Make up a name
2094 	 */
2095 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2096 	tem_dp->name[VIDPIDLEN] = '\0';
2097 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2098 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2099 	/*
2100 	 * 'clean' vendor and product strings of non-printing chars
2101 	 */
2102 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2103 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2104 			tem_dp->name[i] = '.';
2105 		}
2106 	}
2107 
2108 	/*
2109 	 * MODE SENSE to determine block size.
2110 	 */
2111 	un->un_dp->options |= ST_MODE_SEL_COMP;
2112 	if (st_modesense(un)) {
2113 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2114 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2115 		un->un_dp->options &= ~ST_MODE_SEL_COMP;
2116 		kmem_free(tem_dp, sizeof (struct st_drivetype));
2117 		return (0);
2118 	}
2119 
2120 	/* Can mode sense page 0x10 or 0xf */
2121 	tem_dp->options |= ST_MODE_SEL_COMP;
2122 	bsize = (un->un_mspl->high_bl << 16)	|
2123 	    (un->un_mspl->mid_bl << 8)		|
2124 	    (un->un_mspl->low_bl);
2125 
2126 	if (bsize == 0) {
2127 		tem_dp->options |= ST_VARIABLE;
2128 		tem_dp->bsize = 0;
2129 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2130 		if (st_change_block_size(un->un_dev, 0) != 0) {
2131 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2132 			    "st_get_conf_from_tape_drive(): "
2133 			    "Fixed record size is too large and"
2134 			    "cannot switch to variable record size");
2135 			kmem_free(tem_dp, sizeof (struct st_drivetype));
2136 			return (0);
2137 		}
2138 		tem_dp->options |= ST_VARIABLE;
2139 	} else if (st_change_block_size(un->un_dev, 0) == 0) {
2140 		tem_dp->options |= ST_VARIABLE;
2141 		tem_dp->bsize = 0;
2142 	} else {
2143 		tem_dp->bsize = bsize;
2144 	}
2145 
2146 	/*
2147 	 * If READ BLOCk LIMITS works and upper block size limit is
2148 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2149 	 */
2150 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2151 	if (st_read_block_limits(un, blklim) != 0) {
2152 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2153 		    "st_get_conf_from_tape_drive(): "
2154 		    "fail to read block limits.\n");
2155 		kmem_free(blklim, sizeof (struct read_blklim));
2156 		kmem_free(tem_dp, sizeof (struct st_drivetype));
2157 		return (0);
2158 	}
2159 	maxbsize = (blklim->max_hi << 16) +
2160 	    (blklim->max_mid << 8) + blklim->max_lo;
2161 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2162 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2163 	}
2164 	kmem_free(blklim, sizeof (struct read_blklim));
2165 
2166 	/*
2167 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2168 	 */
2169 	buf = kmem_zalloc(6, KM_SLEEP);
2170 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2171 	if (rval != 0) {
2172 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2173 		    "st_get_conf_from_tape_drive(): "
2174 		    "fail to read vitial inquiry.\n");
2175 		kmem_free(buf, 6);
2176 		kmem_free(tem_dp, sizeof (struct st_drivetype));
2177 		return (0);
2178 	}
2179 	if (buf[4] & 1) {
2180 		tem_dp->options |= ST_WORMABLE;
2181 	}
2182 	kmem_free(buf, 6);
2183 
2184 	/* Assume BSD BSR KNOWS_EOD */
2185 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2186 	tem_dp->max_rretries = -1;
2187 	tem_dp->max_wretries = -1;
2188 
2189 	/*
2190 	 * Decide the densities supported by tape drive by sending
2191 	 * REPORT DENSITY SUPPORT command.
2192 	 */
2193 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2194 		kmem_free(tem_dp, sizeof (struct st_drivetype));
2195 		return (0);
2196 	}
2197 
2198 	/*
2199 	 * Decide the timeout values for several commands by sending
2200 	 * REPORT SUPPORTED OPERATION CODES command.
2201 	 */
2202 	if (st_get_timeout_values_from_tape_drive(un, tem_dp) == 0) {
2203 		kmem_free(tem_dp, sizeof (struct st_drivetype));
2204 		return (0);
2205 	}
2206 
2207 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2208 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2209 	return (1);
2210 }
2211 
2212 static int
2213 st_get_densities_from_tape_drive(struct scsi_tape *un,
2214     struct st_drivetype *dp)
2215 {
2216 	int i, p;
2217 	size_t buflen;
2218 	ushort_t des_len;
2219 	uchar_t *den_header;
2220 	uchar_t num_den;
2221 	uchar_t den[NDENSITIES];
2222 	uchar_t deflt[NDENSITIES];
2223 	struct report_density_desc *den_desc;
2224 
2225 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2226 
2227 	/*
2228 	 * Since we have no idea how many densitiy support entries
2229 	 * will be returned, we send the command firstly assuming
2230 	 * there is only one. Then we can decide the number of
2231 	 * entries by available density support length. If multiple
2232 	 * entries exist, we will resend the command with enough
2233 	 * buffer size.
2234 	 */
2235 	buflen = sizeof (struct report_density_header) +
2236 	    sizeof (struct report_density_desc);
2237 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2238 	if (st_report_density_support(un, den_header, buflen) != 0) {
2239 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2240 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2241 		kmem_free(den_header, buflen);
2242 		return (0);
2243 	}
2244 	des_len =
2245 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2246 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2247 
2248 	if (num_den > 1) {
2249 		kmem_free(den_header, buflen);
2250 		buflen = sizeof (struct report_density_header) +
2251 		    sizeof (struct report_density_desc) * num_den;
2252 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2253 		if (st_report_density_support(un, den_header, buflen) != 0) {
2254 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2255 			    "st_get_conf_from_tape_drive(): "
2256 			    "fail to report density.\n");
2257 			kmem_free(den_header, buflen);
2258 			return (0);
2259 		}
2260 	}
2261 
2262 	den_desc = (struct report_density_desc *)(den_header
2263 	    + sizeof (struct report_density_header));
2264 
2265 	/*
2266 	 * Decide the drive type by assigning organization
2267 	 */
2268 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2269 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2270 		    8) == 0) {
2271 			dp->type = st_vid_dt[i].type;
2272 			break;
2273 		}
2274 	}
2275 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2276 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2277 		    "st_get_conf_from_tape_drive(): "
2278 		    "can't find match of assigned ort.\n");
2279 		kmem_free(den_header, buflen);
2280 		return (0);
2281 	}
2282 
2283 	/*
2284 	 * The tape drive may support many tape formats, but the st driver
2285 	 * supports only the four highest densities. Since density code
2286 	 * values are returned by ascending sequence, we start from the
2287 	 * last entry of density support data block descriptor.
2288 	 */
2289 	p = 0;
2290 	den_desc += num_den - 1;
2291 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2292 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2293 			if (p != 0) {
2294 				if (den_desc->pri_den >= den[p - 1]) {
2295 					continue;
2296 				}
2297 			}
2298 			den[p] = den_desc->pri_den;
2299 			deflt[p] = den_desc->deflt;
2300 			p ++;
2301 		}
2302 	}
2303 
2304 	switch (p) {
2305 	case 0:
2306 		bzero(dp->densities, NDENSITIES);
2307 		dp->options |= ST_AUTODEN_OVERRIDE;
2308 		dp->default_density = MT_DENSITY4;
2309 		break;
2310 
2311 	case 1:
2312 		(void) memset(dp->densities, den[0], NDENSITIES);
2313 		dp->options |= ST_AUTODEN_OVERRIDE;
2314 		dp->default_density = MT_DENSITY4;
2315 		break;
2316 
2317 	case 2:
2318 		dp->densities[0] = den[1];
2319 		dp->densities[1] = den[1];
2320 		dp->densities[2] = den[0];
2321 		dp->densities[3] = den[0];
2322 		if (deflt[0]) {
2323 			dp->default_density = MT_DENSITY4;
2324 		} else {
2325 			dp->default_density = MT_DENSITY2;
2326 		}
2327 		break;
2328 
2329 	case 3:
2330 		dp->densities[0] = den[2];
2331 		dp->densities[1] = den[1];
2332 		dp->densities[2] = den[0];
2333 		dp->densities[3] = den[0];
2334 		if (deflt[0]) {
2335 			dp->default_density = MT_DENSITY4;
2336 		} else if (deflt[1]) {
2337 			dp->default_density = MT_DENSITY2;
2338 		} else {
2339 			dp->default_density = MT_DENSITY1;
2340 		}
2341 		break;
2342 
2343 	default:
2344 		for (i = p; i > p - NDENSITIES; i --) {
2345 			dp->densities[i - 1] = den[p - i];
2346 		}
2347 		if (deflt[0]) {
2348 			dp->default_density = MT_DENSITY4;
2349 		} else if (deflt[1]) {
2350 			dp->default_density = MT_DENSITY3;
2351 		} else if (deflt[2]) {
2352 			dp->default_density = MT_DENSITY2;
2353 		} else {
2354 			dp->default_density = MT_DENSITY1;
2355 		}
2356 		break;
2357 	}
2358 
2359 	bzero(dp->mediatype, NDENSITIES);
2360 
2361 	kmem_free(den_header, buflen);
2362 	return (1);
2363 }
2364 
2365 static int
2366 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2367     struct st_drivetype *dp)
2368 {
2369 	ushort_t timeout;
2370 
2371 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2372 
2373 	if (st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0) != 0) {
2374 		return (0);
2375 	}
2376 	dp->erase_timeout = timeout;
2377 
2378 	if (st_get_timeouts_value(un, SCMD_READ, &timeout, 0) != 0) {
2379 		return (0);
2380 	}
2381 	dp->io_timeout = timeout;
2382 
2383 	if (st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0) != 0) {
2384 		return (0);
2385 	}
2386 	dp->io_timeout = max(dp->io_timeout, timeout);
2387 
2388 	if (st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0) != 0) {
2389 		return (0);
2390 	}
2391 	dp->space_timeout = timeout;
2392 
2393 	if (st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0) != 0) {
2394 		return (0);
2395 	}
2396 	dp->load_timeout = timeout;
2397 	dp->unload_timeout = timeout;
2398 
2399 	if (st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0) != 0) {
2400 		return (0);
2401 	}
2402 	dp->rewind_timeout = timeout;
2403 
2404 	if (st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0) != 0) {
2405 		return (0);
2406 	}
2407 	dp->non_motion_timeout = timeout;
2408 
2409 	return (1);
2410 }
2411 
2412 static int
2413 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2414     ushort_t *timeout_value, ushort_t service_action)
2415 {
2416 	uchar_t *timeouts;
2417 	uchar_t *oper;
2418 	uchar_t support;
2419 	uchar_t cdbsize;
2420 	uchar_t ctdp;
2421 	size_t buflen;
2422 	int rval;
2423 
2424 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2425 
2426 	buflen = sizeof (struct one_com_des) +
2427 	    sizeof (struct com_timeout_des);
2428 	oper = kmem_zalloc(buflen, KM_SLEEP);
2429 	rval = st_report_supported_operation(un, oper, option_code,
2430 	    service_action);
2431 
2432 	if (rval != 0) {
2433 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2434 		    "st_get_timeouts_value(): "
2435 		    "fail to timeouts value for command %d.\n", option_code);
2436 		kmem_free(oper, buflen);
2437 		return (rval);
2438 	}
2439 
2440 	support = ((struct one_com_des *)oper)->support;
2441 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2442 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2443 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2444 		    "st_get_timeouts_value(): "
2445 		    "command %d is not supported.\n", option_code);
2446 		kmem_free(oper, buflen);
2447 		return (-1);
2448 	}
2449 
2450 	ctdp = ((struct one_com_des *)oper)->ctdp;
2451 	if (!ctdp) {
2452 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2453 		    "st_get_timeouts_value(): "
2454 		    "command timeout is not included.\n");
2455 		kmem_free(oper, buflen);
2456 		return (-1);
2457 	}
2458 
2459 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2460 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2461 
2462 	/*
2463 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2464 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2465 	 * to 0xFFFF.
2466 	 */
2467 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2468 		*timeout_value = USHRT_MAX;
2469 	} else {
2470 		*timeout_value = ((*(timeouts + 10)) << 8) |
2471 		    (*(timeouts + 11));
2472 	}
2473 
2474 	kmem_free(oper, buflen);
2475 	return (0);
2476 }
2477 
2478 static int
2479 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2480 {
2481 	int i;
2482 
2483 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2484 
2485 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2486 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2487 
2488 	/*
2489 	 * Make up a name
2490 	 */
2491 	bcopy("Vendor '", dp->name, 8);
2492 	bcopy(vidpid, &dp->name[8], VIDLEN);
2493 	bcopy("' Product '", &dp->name[16], 11);
2494 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2495 	dp->name[ST_NAMESIZE - 2] = '\'';
2496 	dp->name[ST_NAMESIZE - 1] = '\0';
2497 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2498 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2499 	/*
2500 	 * 'clean' vendor and product strings of non-printing chars
2501 	 */
2502 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2503 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2504 			dp->name[i] = '.';
2505 		}
2506 	}
2507 	dp->type = ST_TYPE_INVALID;
2508 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2509 
2510 	return (1); /* Can Not Fail */
2511 }
2512 
2513 /*
2514  * Regular Unix Entry points
2515  */
2516 
2517 
2518 
2519 /* ARGSUSED */
2520 static int
2521 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2522 {
2523 	dev_t dev = *dev_p;
2524 	int rval = 0;
2525 
2526 	GET_SOFT_STATE(dev);
2527 
2528 	ST_ENTR(ST_DEVINFO, st_open);
2529 
2530 	/*
2531 	 * validate that we are addressing a sensible unit
2532 	 */
2533 	mutex_enter(ST_MUTEX);
2534 
2535 #ifdef	STDEBUG
2536 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2537 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2538 	    st_dev_name(dev), *dev_p, flag, otyp);
2539 #endif
2540 
2541 	/*
2542 	 * All device accesss go thru st_strategy() where we check
2543 	 * suspend status
2544 	 */
2545 
2546 	if (!un->un_attached) {
2547 		st_known_tape_type(un);
2548 		if (!un->un_attached) {
2549 			rval = ENXIO;
2550 			goto exit;
2551 		}
2552 
2553 	}
2554 
2555 	/*
2556 	 * Check for the case of the tape in the middle of closing.
2557 	 * This isn't simply a check of the current state, because
2558 	 * we could be in state of sensing with the previous state
2559 	 * that of closing.
2560 	 *
2561 	 * And don't allow multiple opens.
2562 	 */
2563 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2564 		un->un_laststate = un->un_state;
2565 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2566 		while (IS_CLOSING(un) ||
2567 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2568 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2569 				rval = EINTR;
2570 				un->un_state = un->un_laststate;
2571 				goto exit;
2572 			}
2573 		}
2574 	} else if (un->un_state != ST_STATE_CLOSED) {
2575 		rval = EBUSY;
2576 		goto busy;
2577 	}
2578 
2579 	/*
2580 	 * record current dev
2581 	 */
2582 	un->un_dev = dev;
2583 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2584 	un->un_errno = 0;	/* no errors yet */
2585 	un->un_restore_pos = 0;
2586 	un->un_rqs_state = 0;
2587 
2588 	/*
2589 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2590 	 * anything, leave internal states alone, if fileno >= 0
2591 	 */
2592 	if (flag & (FNDELAY | FNONBLOCK)) {
2593 		switch (un->un_pos.pmode) {
2594 
2595 		case invalid:
2596 			un->un_state = ST_STATE_OFFLINE;
2597 			break;
2598 
2599 		case legacy:
2600 			/*
2601 			 * If position is anything other than rewound.
2602 			 */
2603 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2604 				/*
2605 				 * set un_read_only/write-protect status.
2606 				 *
2607 				 * If the tape is not bot we can assume
2608 				 * that mspl->wp_status is set properly.
2609 				 * else
2610 				 * we need to do a mode sense/Tur once
2611 				 * again to get the actual tape status.(since
2612 				 * user might have replaced the tape)
2613 				 * Hence make the st state OFFLINE so that
2614 				 * we re-intialize the tape once again.
2615 				 */
2616 				un->un_read_only =
2617 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2618 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2619 			} else {
2620 				un->un_state = ST_STATE_OFFLINE;
2621 			}
2622 			break;
2623 		case logical:
2624 			/* swag not sure how we were open last time */
2625 			(void) st_update_block_pos(un);
2626 			if (un->un_pos.lgclblkno == 0) {
2627 				un->un_state = ST_STATE_OFFLINE;
2628 			} else {
2629 				un->un_read_only =
2630 				    (un->un_oflags & FWRITE) ? 0 : 1;
2631 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2632 			}
2633 			break;
2634 		}
2635 		rval = 0;
2636 	} else {
2637 		/*
2638 		 * Not opening O_NDELAY.
2639 		 */
2640 		un->un_state = ST_STATE_OPENING;
2641 
2642 		/*
2643 		 * Clear error entry stack
2644 		 */
2645 		st_empty_error_stack(un);
2646 
2647 		rval = st_tape_init(dev);
2648 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2649 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2650 			rval = 0; /* so open doesn't fail */
2651 		} else if (rval) {
2652 			/*
2653 			 * Release the tape unit, if reserved and not
2654 			 * preserve reserve.
2655 			 */
2656 			if ((un->un_rsvd_status &
2657 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2658 				(void) st_reserve_release(un, ST_RELEASE);
2659 			}
2660 		} else {
2661 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2662 		}
2663 	}
2664 
2665 exit:
2666 	/*
2667 	 * we don't want any uninvited guests scrogging our data when we're
2668 	 * busy with something, so for successful opens or failed opens
2669 	 * (except for EBUSY), reset these counters and state appropriately.
2670 	 */
2671 	if (rval != EBUSY) {
2672 		if (rval) {
2673 			un->un_state = ST_STATE_CLOSED;
2674 		}
2675 		un->un_err_resid = 0;
2676 		un->un_retry_ct = 0;
2677 		un->un_tran_retry_ct = 0;
2678 	}
2679 busy:
2680 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2681 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2682 	mutex_exit(ST_MUTEX);
2683 	return (rval);
2684 
2685 }
2686 
2687 static int
2688 st_tape_init(dev_t dev)
2689 {
2690 	int err;
2691 	int rval = 0;
2692 
2693 	GET_SOFT_STATE(dev);
2694 
2695 	ST_FUNC(ST_DEVINFO, st_tape_init);
2696 
2697 	ASSERT(mutex_owned(ST_MUTEX));
2698 
2699 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2700 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2701 
2702 	/*
2703 	 * Clean up after any errors left by 'last' close.
2704 	 * This also handles the case of the initial open.
2705 	 */
2706 	if (un->un_state != ST_STATE_INITIALIZING) {
2707 		un->un_laststate = un->un_state;
2708 		un->un_state = ST_STATE_OPENING;
2709 	}
2710 
2711 	un->un_kbytes_xferred = 0;
2712 
2713 	/*
2714 	 * do a throw away TUR to clear check condition
2715 	 */
2716 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2717 
2718 	/*
2719 	 * If test unit ready fails because the drive is reserved
2720 	 * by another host fail the open for no access.
2721 	 */
2722 	if (err) {
2723 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2724 			un->un_state = ST_STATE_CLOSED;
2725 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2726 			    "st_tape_init: RESERVATION CONFLICT\n");
2727 			rval = EACCES;
2728 			goto exit;
2729 		}
2730 	}
2731 
2732 	/*
2733 	 * See whether this is a generic device that we haven't figured
2734 	 * anything out about yet.
2735 	 */
2736 	if (un->un_dp->type == ST_TYPE_INVALID) {
2737 		rval = st_determine_generic(dev);
2738 		if (rval) {
2739 			if (rval != EACCES) {
2740 				rval = EIO;
2741 			}
2742 			un->un_state = ST_STATE_CLOSED;
2743 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2744 			    "st_tape_init: %s invalid type\n",
2745 			    rval == EACCES ? "EACCES" : "EIO");
2746 			goto exit;
2747 		}
2748 		/*
2749 		 * If this is a Unknown Type drive,
2750 		 * Use the READ BLOCK LIMITS to determine if
2751 		 * allow large xfer is approprate if not globally
2752 		 * disabled with st_allow_large_xfer.
2753 		 */
2754 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2755 	} else {
2756 
2757 		/*
2758 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2759 		 * the max block size supported by the drive,
2760 		 * find it by issueing a READ_BLKLIM command.
2761 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2762 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2763 		 */
2764 		un->un_allow_large_xfer = st_allow_large_xfer &&
2765 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2766 	}
2767 	/*
2768 	 * if maxbsize is unknown, set the maximum block size.
2769 	 */
2770 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2771 
2772 		/*
2773 		 * Get the Block limits of the tape drive.
2774 		 * if un->un_allow_large_xfer = 0 , then make sure
2775 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2776 		 */
2777 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2778 
2779 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2780 		if (err) {
2781 			/* Retry */
2782 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2783 		}
2784 		if (!err) {
2785 
2786 			/*
2787 			 * if cmd successful, use limit returned
2788 			 */
2789 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2790 			    (un->un_rbl->max_mid << 8) +
2791 			    un->un_rbl->max_lo;
2792 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2793 			    un->un_rbl->min_lo;
2794 			un->un_data_mod = 1 << un->un_rbl->granularity;
2795 			if ((un->un_maxbsize == 0) ||
2796 			    (un->un_allow_large_xfer == 0 &&
2797 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2798 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2799 
2800 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2801 				/*
2802 				 * Drive is not one that is configured, But the
2803 				 * READ BLOCK LIMITS tells us it can do large
2804 				 * xfers.
2805 				 */
2806 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2807 					un->un_dp->options |=
2808 					    ST_NO_RECSIZE_LIMIT;
2809 				}
2810 				/*
2811 				 * If max and mimimum block limits are the
2812 				 * same this is a fixed block size device.
2813 				 */
2814 				if (un->un_maxbsize == un->un_minbsize) {
2815 					un->un_dp->options &= ~ST_VARIABLE;
2816 				}
2817 			}
2818 
2819 			if (un->un_minbsize == 0) {
2820 				un->un_minbsize = 1;
2821 			}
2822 
2823 		} else { /* error on read block limits */
2824 
2825 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2826 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
2827 			    " errno = %d un_rsvd_status = 0x%X\n",
2828 			    err, un->un_rsvd_status);
2829 
2830 			/*
2831 			 * since read block limits cmd failed,
2832 			 * do not allow large xfers.
2833 			 * use old values in st_minphys
2834 			 */
2835 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2836 				rval = EACCES;
2837 			} else {
2838 				un->un_allow_large_xfer = 0;
2839 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2840 				    "!Disabling large transfers\n");
2841 
2842 				/*
2843 				 * we guess maxbsize and minbsize
2844 				 */
2845 				if (un->un_bsize) {
2846 					un->un_maxbsize = un->un_minbsize =
2847 					    un->un_bsize;
2848 				} else {
2849 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2850 					un->un_minbsize = 1;
2851 				}
2852 				/*
2853 				 * Data Mod must be set,
2854 				 * Even if read block limits fails.
2855 				 * Prevents Divide By Zero in st_rw().
2856 				 */
2857 				un->un_data_mod = 1;
2858 			}
2859 		}
2860 		if (un->un_rbl) {
2861 			kmem_free(un->un_rbl, RBLSIZE);
2862 			un->un_rbl = NULL;
2863 		}
2864 
2865 		if (rval) {
2866 			goto exit;
2867 		}
2868 	}
2869 
2870 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2871 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2872 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2873 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2874 
2875 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2876 
2877 	if (err != 0) {
2878 		if (err == EINTR) {
2879 			un->un_laststate = un->un_state;
2880 			un->un_state = ST_STATE_CLOSED;
2881 			rval = EINTR;
2882 			goto exit;
2883 		}
2884 		/*
2885 		 * Make sure the tape is ready
2886 		 */
2887 		un->un_pos.pmode = invalid;
2888 		if (un->un_status != KEY_UNIT_ATTENTION) {
2889 			/*
2890 			 * allow open no media.  Subsequent MTIOCSTATE
2891 			 * with media present will complete the open
2892 			 * logic.
2893 			 */
2894 			un->un_laststate = un->un_state;
2895 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2896 				un->un_mediastate = MTIO_EJECTED;
2897 				un->un_state = ST_STATE_OFFLINE;
2898 				rval = 0;
2899 				goto exit;
2900 			} else {
2901 				un->un_state = ST_STATE_CLOSED;
2902 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2903 				    "st_tape_init EIO no media, not opened "
2904 				    "O_NONBLOCK|O_EXCL\n");
2905 				rval = EIO;
2906 				goto exit;
2907 			}
2908 		}
2909 	}
2910 
2911 	/*
2912 	 * On each open, initialize block size from drivetype struct,
2913 	 * as it could have been changed by MTSRSZ ioctl.
2914 	 * Now, ST_VARIABLE simply means drive is capable of variable
2915 	 * mode. All drives are assumed to support fixed records.
2916 	 * Hence, un_bsize tells what mode the drive is in.
2917 	 *	un_bsize	= 0	- variable record length
2918 	 *			= x	- fixed record length is x
2919 	 */
2920 	un->un_bsize = un->un_dp->bsize;
2921 
2922 	/*
2923 	 * If saved position is valid go there
2924 	 */
2925 	if (un->un_restore_pos) {
2926 		rval = st_validate_tapemarks(un, &un->un_pos);
2927 		if (rval != 0) {
2928 			if (rval != EACCES) {
2929 				rval = EIO;
2930 			}
2931 			un->un_restore_pos = 0;
2932 			un->un_laststate = un->un_state;
2933 			un->un_state = ST_STATE_CLOSED;
2934 			goto exit;
2935 		}
2936 		un->un_pos.fileno = un->un_save_fileno;
2937 		un->un_pos.blkno = un->un_save_blkno;
2938 		un->un_restore_pos = 0;
2939 	}
2940 
2941 	if (un->un_pos.pmode == invalid) {
2942 		rval = st_loadtape(dev);
2943 		if (rval) {
2944 			if (rval != EACCES) {
2945 				rval = EIO;
2946 			}
2947 			un->un_laststate = un->un_state;
2948 			un->un_state = ST_STATE_CLOSED;
2949 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2950 			    "st_tape_init: %s can't open tape\n",
2951 			    rval == EACCES ? "EACCES" : "EIO");
2952 			goto exit;
2953 		}
2954 	}
2955 
2956 	/*
2957 	 * do a mode sense to pick up state of current write-protect,
2958 	 * Could cause reserve and fail due to conflict.
2959 	 */
2960 	rval = st_modesense(un);
2961 	if (rval == EACCES) {
2962 		goto exit;
2963 	}
2964 
2965 	/*
2966 	 * If we are opening the tape for writing, check
2967 	 * to make sure that the tape can be written.
2968 	 */
2969 	if (un->un_oflags & FWRITE) {
2970 		err = 0;
2971 		if (un->un_mspl->wp) {
2972 			un->un_status = KEY_WRITE_PROTECT;
2973 			un->un_laststate = un->un_state;
2974 			un->un_state = ST_STATE_CLOSED;
2975 			rval = EACCES;
2976 			/*
2977 			 * STK sets the wp bit if volsafe tape is loaded.
2978 			 */
2979 			if ((un->un_dp->type == MT_ISSTK9840) &&
2980 			    (un->un_dp->options & ST_WORMABLE)) {
2981 				un->un_read_only = RDONLY;
2982 			} else {
2983 				goto exit;
2984 			}
2985 		} else {
2986 			un->un_read_only = RDWR;
2987 		}
2988 	} else {
2989 		un->un_read_only = RDONLY;
2990 	}
2991 
2992 	if (un->un_dp->options & ST_WORMABLE) {
2993 		un->un_read_only |= un->un_wormable(un);
2994 
2995 		if (((un->un_read_only == WORM) ||
2996 		    (un->un_read_only == RDWORM)) &&
2997 		    ((un->un_oflags & FWRITE) == FWRITE)) {
2998 			un->un_status = KEY_DATA_PROTECT;
2999 			rval = EACCES;
3000 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3001 			    "read_only = %d eof = %d oflag = %d\n",
3002 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3003 		}
3004 	}
3005 
3006 	/*
3007 	 * If we're opening the tape write-only, we need to
3008 	 * write 2 filemarks on the HP 1/2 inch drive, to
3009 	 * create a null file.
3010 	 */
3011 	if ((un->un_read_only == RDWR) ||
3012 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3013 		if (un->un_dp->options & ST_REEL) {
3014 			un->un_fmneeded = 2;
3015 		} else {
3016 			un->un_fmneeded = 1;
3017 		}
3018 	} else {
3019 		un->un_fmneeded = 0;
3020 	}
3021 
3022 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3023 	    "fmneeded = %x\n", un->un_fmneeded);
3024 
3025 	/*
3026 	 * Make sure the density can be selected correctly.
3027 	 * If WORM can only write at the append point which in most cases
3028 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3029 	 * to set and try densities if a BOP.
3030 	 */
3031 	if (st_determine_density(dev,
3032 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3033 		un->un_status = KEY_ILLEGAL_REQUEST;
3034 		un->un_laststate = un->un_state;
3035 		un->un_state = ST_STATE_CLOSED;
3036 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3037 		    "st_tape_init: EIO can't determine density\n");
3038 		rval = EIO;
3039 		goto exit;
3040 	}
3041 
3042 	/*
3043 	 * Destroy the knowledge that we have 'determined'
3044 	 * density so that a later read at BOT comes along
3045 	 * does the right density determination.
3046 	 */
3047 
3048 	un->un_density_known = 0;
3049 
3050 
3051 	/*
3052 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3053 	 * Mark the state such that any I/O or tape space operations
3054 	 * will get/set the right density, etc..
3055 	 */
3056 	un->un_laststate = un->un_state;
3057 	un->un_lastop = ST_OP_NIL;
3058 	un->un_mediastate = MTIO_INSERTED;
3059 	cv_broadcast(&un->un_state_cv);
3060 
3061 	/*
3062 	 *  Set test append flag if writing.
3063 	 *  First write must check that tape is positioned correctly.
3064 	 */
3065 	un->un_test_append = (un->un_oflags & FWRITE);
3066 
3067 exit:
3068 	un->un_err_resid = 0;
3069 	un->un_last_resid = 0;
3070 	un->un_last_count = 0;
3071 
3072 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3073 	    "st_tape_init: return val = %x\n", rval);
3074 	return (rval);
3075 
3076 }
3077 
3078 
3079 
3080 /* ARGSUSED */
3081 static int
3082 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3083 {
3084 	int err = 0;
3085 	int norew, count, last_state;
3086 #ifdef	__x86
3087 	struct contig_mem *cp, *cp_temp;
3088 #endif
3089 
3090 	GET_SOFT_STATE(dev);
3091 
3092 	ST_ENTR(ST_DEVINFO, st_close);
3093 
3094 	/*
3095 	 * wait till all cmds in the pipeline have been completed
3096 	 */
3097 	mutex_enter(ST_MUTEX);
3098 
3099 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3100 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3101 
3102 	st_wait_for_io(un);
3103 
3104 	/* turn off persistent errors on close, as we want close to succeed */
3105 	TURN_PE_OFF(un);
3106 
3107 	/*
3108 	 * set state to indicate that we are in process of closing
3109 	 */
3110 	last_state = un->un_laststate = un->un_state;
3111 	un->un_state = ST_STATE_CLOSING;
3112 
3113 	/*
3114 	 * BSD behavior:
3115 	 * a close always causes a silent span to the next file if we've hit
3116 	 * an EOF (but not yet read across it).
3117 	 */
3118 #ifdef DEBUG
3119 	if ((st_debug & 0xf) >= 6)
3120 		st_print_position(un, "st_close1:", &un->un_pos);
3121 #endif
3122 
3123 	if (BSD_BEHAVIOR && (un->un_pos.eof == ST_EOF)) {
3124 		if (un->un_pos.pmode != invalid) {
3125 			un->un_pos.fileno++;
3126 			un->un_pos.blkno = 0;
3127 		}
3128 		un->un_pos.eof = ST_NO_EOF;
3129 	}
3130 
3131 	/*
3132 	 * rewinding?
3133 	 */
3134 	norew = (getminor(dev) & MT_NOREWIND);
3135 
3136 	/*
3137 	 * SVR4 behavior for skipping to next file:
3138 	 *
3139 	 * If we have not seen a filemark, space to the next file
3140 	 *
3141 	 * If we have already seen the filemark we are physically in the next
3142 	 * file and we only increment the filenumber
3143 	 */
3144 
3145 
3146 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) &&
3147 	    (un->un_pos.blkno != 0) &&
3148 	    ((un->un_lastop != ST_OP_WRITE) && (un->un_lastop != ST_OP_WEOF))) {
3149 		switch (un->un_pos.eof) {
3150 		case ST_NO_EOF:
3151 			/*
3152 			 * if we were reading and did not read the complete file
3153 			 * skip to the next file, leaving the tape correctly
3154 			 * positioned to read the first record of the next file
3155 			 * Check first for REEL if we are at EOT by trying to
3156 			 * read a block
3157 			 */
3158 			if ((un->un_dp->options & ST_REEL) &&
3159 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3160 			    (un->un_pos.blkno == 0)) {
3161 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3162 					ST_DEBUG2(ST_DEVINFO, st_label,
3163 					    SCSI_DEBUG,
3164 					    "st_close : EIO can't space\n");
3165 					err = EIO;
3166 					break;
3167 				}
3168 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3169 					un->un_pos.eof = ST_EOT_PENDING;
3170 					un->un_pos.fileno += 1;
3171 					un->un_pos.blkno   = 0;
3172 					break;
3173 				}
3174 			}
3175 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3176 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3177 				    "st_close: EIO can't space #2\n");
3178 				err = EIO;
3179 			} else {
3180 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3181 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3182 				    un->un_pos.fileno, un->un_pos.blkno,
3183 				    un->un_pos.eof);
3184 				un->un_pos.eof = ST_NO_EOF;
3185 			}
3186 			break;
3187 
3188 		case ST_EOF_PENDING:
3189 		case ST_EOF:
3190 			un->un_pos.fileno += 1;
3191 			un->un_pos.blkno   = 0;
3192 			un->un_pos.eof = ST_NO_EOF;
3193 			break;
3194 
3195 		case ST_EOT:
3196 		case ST_EOT_PENDING:
3197 			/* nothing to do */
3198 			break;
3199 		default:
3200 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
3201 			    "Undefined state 0x%x", un->un_pos.eof);
3202 
3203 		}
3204 	}
3205 
3206 
3207 	/*
3208 	 * For performance reasons (HP 88780), the driver should
3209 	 * postpone writing the second tape mark until just before a file
3210 	 * positioning ioctl is issued (e.g., rewind).	This means that
3211 	 * the user must not manually rewind the tape because the tape will
3212 	 * be missing the second tape mark which marks EOM.
3213 	 * However, this small performance improvement is not worth the risk.
3214 	 */
3215 
3216 	/*
3217 	 * We need to back up over the filemark we inadvertently popped
3218 	 * over doing a read in between the two filemarks that constitute
3219 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3220 	 * set while reading.
3221 	 *
3222 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3223 	 * the writing of filemark(s) will clear the ST_EOM state, which
3224 	 * we don't want, so we save this state and restore it later.
3225 	 */
3226 
3227 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3228 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3229 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3230 
3231 	if (un->un_pos.eof == ST_EOT_PENDING) {
3232 		if (norew) {
3233 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3234 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3235 				    "st_close: EIO can't space #3\n");
3236 				err = EIO;
3237 			} else {
3238 				un->un_pos.blkno = 0;
3239 				un->un_pos.eof = ST_EOT;
3240 			}
3241 		} else {
3242 			un->un_pos.eof = ST_NO_EOF;
3243 		}
3244 
3245 	/*
3246 	 * Do we need to write a file mark?
3247 	 *
3248 	 * only write filemarks if there are fmks to be written and
3249 	 *   - open for write (possibly read/write)
3250 	 *   - the last operation was a write
3251 	 * or:
3252 	 *   -	opened for wronly
3253 	 *   -	no data was written
3254 	 */
3255 	} else if ((un->un_pos.pmode != invalid) && (un->un_fmneeded > 0) &&
3256 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
3257 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
3258 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3259 
3260 		/* save ST_EOM state */
3261 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3262 
3263 		/*
3264 		 * Note that we will write a filemark if we had opened
3265 		 * the tape write only and no data was written, thus
3266 		 * creating a null file.
3267 		 *
3268 		 * If the user already wrote one, we only have to write 1 more.
3269 		 * If they wrote two, we don't have to write any.
3270 		 */
3271 
3272 		count = un->un_fmneeded;
3273 		if (count > 0) {
3274 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
3275 			    count, SYNC_CMD)) {
3276 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3277 				    "st_close : EIO can't wfm\n");
3278 				err = EIO;
3279 			}
3280 			if ((un->un_dp->options & ST_REEL) && norew) {
3281 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
3282 				    SYNC_CMD)) {
3283 					ST_DEBUG2(ST_DEVINFO, st_label,
3284 					    SCSI_DEBUG,
3285 					    "st_close : EIO space fmk(-1)\n");
3286 					err = EIO;
3287 				}
3288 				un->un_pos.eof = ST_NO_EOF;
3289 				/* fix up block number */
3290 				un->un_pos.blkno = 0;
3291 			}
3292 		}
3293 
3294 		/*
3295 		 * If we aren't going to be rewinding, and we were at
3296 		 * physical eot, restore the state that indicates we
3297 		 * are at physical eot. Once you have reached physical
3298 		 * eot, and you close the tape, the only thing you can
3299 		 * do on the next open is to rewind. Access to trailer
3300 		 * records is only allowed without closing the device.
3301 		 */
3302 		if (norew == 0 && was_at_eom) {
3303 			un->un_pos.eof = ST_EOM;
3304 		}
3305 	}
3306 
3307 	/*
3308 	 * report soft errors if enabled and available, if we never accessed
3309 	 * the drive, don't get errors. This will prevent some DAT error
3310 	 * messages upon LOG SENSE.
3311 	 */
3312 	if (st_report_soft_errors_on_close &&
3313 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3314 	    (last_state != ST_STATE_OFFLINE)) {
3315 		(void) st_report_soft_errors(dev, flag);
3316 	}
3317 
3318 
3319 	/*
3320 	 * Do we need to rewind? Can we rewind?
3321 	 */
3322 	if (norew == 0 && un->un_pos.pmode != invalid && err == 0) {
3323 		/*
3324 		 * We'd like to rewind with the
3325 		 * 'immediate' bit set, but this
3326 		 * causes problems on some drives
3327 		 * where subsequent opens get a
3328 		 * 'NOT READY' error condition
3329 		 * back while the tape is rewinding,
3330 		 * which is impossible to distinguish
3331 		 * from the condition of 'no tape loaded'.
3332 		 *
3333 		 * Also, for some targets, if you disconnect
3334 		 * with the 'immediate' bit set, you don't
3335 		 * actually return right away, i.e., the
3336 		 * target ignores your request for immediate
3337 		 * return.
3338 		 *
3339 		 * Instead, we'll fire off an async rewind
3340 		 * command. We'll mark the device as closed,
3341 		 * and any subsequent open will stall on
3342 		 * the first TEST_UNIT_READY until the rewind
3343 		 * completes.
3344 		 */
3345 
3346 		/*
3347 		 * Used to be if reserve was not supported we'd send an
3348 		 * asynchronious rewind. Comments above may be slightly invalid
3349 		 * as the immediate bit was never set. Doing an immedate rewind
3350 		 * makes sense, I think fixes to not ready status might handle
3351 		 * the problems described above.
3352 		 */
3353 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3354 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
3355 		} else {
3356 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
3357 		}
3358 	}
3359 
3360 	/*
3361 	 * eject tape if necessary
3362 	 */
3363 	if (un->un_eject_tape_on_failure) {
3364 		un->un_eject_tape_on_failure = 0;
3365 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3366 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3367 			    "st_close : can't unload tape\n");
3368 		} else {
3369 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3370 			    "st_close : tape unloaded \n");
3371 			un->un_pos.eof = ST_NO_EOF;
3372 			un->un_mediastate = MTIO_EJECTED;
3373 		}
3374 	}
3375 	/*
3376 	 * Release the tape unit, if default reserve/release
3377 	 * behaviour.
3378 	 */
3379 	if ((un->un_rsvd_status &
3380 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3381 		(void) st_reserve_release(un, ST_RELEASE);
3382 	}
3383 
3384 	/*
3385 	 * clear up state
3386 	 */
3387 	un->un_laststate = un->un_state;
3388 	un->un_state = ST_STATE_CLOSED;
3389 	un->un_lastop = ST_OP_NIL;
3390 	un->un_throttle = 1;	/* assume one request at time, for now */
3391 	un->un_retry_ct = 0;
3392 	un->un_tran_retry_ct = 0;
3393 	un->un_errno = 0;
3394 	un->un_swr_token = (opaque_t)NULL;
3395 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3396 
3397 	/* Restore the options to the init time settings */
3398 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3399 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3400 	} else {
3401 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3402 	}
3403 
3404 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3405 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3406 	} else {
3407 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3408 	}
3409 
3410 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3411 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3412 	} else {
3413 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3414 	}
3415 
3416 	ASSERT(mutex_owned(ST_MUTEX));
3417 
3418 	/*
3419 	 * Signal anyone awaiting a close operation to complete.
3420 	 */
3421 	cv_signal(&un->un_clscv);
3422 
3423 	/*
3424 	 * any kind of error on closing causes all state to be tossed
3425 	 */
3426 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3427 		/*
3428 		 * note that st_intr has already set
3429 		 * un_pos.pmode to invalid.
3430 		 */
3431 		un->un_density_known = 0;
3432 	}
3433 
3434 #ifdef	__x86
3435 	/*
3436 	 * free any contiguous mem alloc'ed for big block I/O
3437 	 */
3438 	cp = un->un_contig_mem;
3439 	while (cp) {
3440 		if (cp->cm_addr) {
3441 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3442 		}
3443 		cp_temp = cp;
3444 		cp = cp->cm_next;
3445 		kmem_free(cp_temp,
3446 		    sizeof (struct contig_mem) + biosize());
3447 	}
3448 	un->un_contig_mem_total_num = 0;
3449 	un->un_contig_mem_available_num = 0;
3450 	un->un_contig_mem = NULL;
3451 	un->un_max_contig_mem_len = 0;
3452 #endif
3453 
3454 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3455 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3456 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3457 
3458 	mutex_exit(ST_MUTEX);
3459 	return (err);
3460 }
3461 
3462 /*
3463  * These routines perform raw i/o operations.
3464  */
3465 
3466 /* ARGSUSED2 */
3467 static int
3468 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3469 {
3470 #ifdef DEBUG
3471 	GET_SOFT_STATE(dev);
3472 	ST_ENTR(ST_DEVINFO, st_aread);
3473 #endif
3474 	return (st_arw(dev, aio, B_READ));
3475 }
3476 
3477 
3478 /* ARGSUSED2 */
3479 static int
3480 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3481 {
3482 #ifdef DEBUG
3483 	GET_SOFT_STATE(dev);
3484 	ST_ENTR(ST_DEVINFO, st_awrite);
3485 #endif
3486 	return (st_arw(dev, aio, B_WRITE));
3487 }
3488 
3489 
3490 
3491 /* ARGSUSED */
3492 static int
3493 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3494 {
3495 #ifdef DEBUG
3496 	GET_SOFT_STATE(dev);
3497 	ST_ENTR(ST_DEVINFO, st_read);
3498 #endif
3499 	return (st_rw(dev, uiop, B_READ));
3500 }
3501 
3502 /* ARGSUSED */
3503 static int
3504 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3505 {
3506 #ifdef DEBUG
3507 	GET_SOFT_STATE(dev);
3508 	ST_ENTR(ST_DEVINFO, st_write);
3509 #endif
3510 	return (st_rw(dev, uiop, B_WRITE));
3511 }
3512 
3513 /*
3514  * Due to historical reasons, old limits are: For variable-length devices:
3515  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3516  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3517  * (let it through unmodified. For fixed-length record devices:
3518  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3519  *
3520  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3521  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3522  * command to the drive).
3523  *
3524  */
3525 static void
3526 st_minphys(struct buf *bp)
3527 {
3528 	struct scsi_tape *un;
3529 
3530 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3531 
3532 	ST_FUNC(ST_DEVINFO, st_minphys);
3533 
3534 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3535 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3536 	    bp->b_bcount);
3537 
3538 	if (un->un_allow_large_xfer) {
3539 
3540 		/*
3541 		 * check un_maxbsize for variable length devices only
3542 		 */
3543 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3544 			bp->b_bcount = un->un_maxbsize;
3545 		}
3546 		/*
3547 		 * can't go more that HBA maxdma limit in either fixed-length
3548 		 * or variable-length tape drives.
3549 		 */
3550 		if (bp->b_bcount > un->un_maxdma) {
3551 			bp->b_bcount = un->un_maxdma;
3552 		}
3553 	} else {
3554 
3555 		/*
3556 		 *  use old fixed limits
3557 		 */
3558 		if (un->un_bsize == 0) {
3559 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3560 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3561 			}
3562 		} else {
3563 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3564 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3565 			}
3566 		}
3567 	}
3568 
3569 	/*
3570 	 * For regular raw I/O and Fixed Block length devices, make sure
3571 	 * the adjusted block count is a whole multiple of the device
3572 	 * block size.
3573 	 */
3574 	if (bp != un->un_sbufp && un->un_bsize) {
3575 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3576 	}
3577 }
3578 
3579 static int
3580 st_rw(dev_t dev, struct uio *uio, int flag)
3581 {
3582 	int rval = 0;
3583 	long len;
3584 
3585 	GET_SOFT_STATE(dev);
3586 
3587 	ST_FUNC(ST_DEVINFO, st_rw);
3588 
3589 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3590 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3591 	    (flag == B_READ ? rd_str: wr_str));
3592 
3593 	/* get local copy of transfer length */
3594 	len = uio->uio_iov->iov_len;
3595 
3596 	mutex_enter(ST_MUTEX);
3597 
3598 	/*
3599 	 * Clear error entry stack
3600 	 */
3601 	st_empty_error_stack(un);
3602 
3603 	/*
3604 	 * If in fixed block size mode and requested read or write
3605 	 * is not an even multiple of that block size.
3606 	 */
3607 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3608 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3609 		    "%s: not modulo %d block size\n",
3610 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3611 		rval = EINVAL;
3612 	}
3613 
3614 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3615 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3616 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3617 		    "%s: not modulo %d device granularity\n",
3618 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3619 		rval = EINVAL;
3620 	}
3621 
3622 	if (rval != 0) {
3623 		un->un_errno = rval;
3624 		mutex_exit(ST_MUTEX);
3625 		return (rval);
3626 	}
3627 
3628 	/*
3629 	 * Reset this so it can be set if Berkeley and read over a filemark.
3630 	 */
3631 	un->un_silent_skip = 0;
3632 	mutex_exit(ST_MUTEX);
3633 
3634 	len = uio->uio_resid;
3635 
3636 	rval = physio(st_strategy, (struct buf *)NULL,
3637 	    dev, flag, st_minphys, uio);
3638 	/*
3639 	 * if we have hit logical EOT during this xfer and there is not a
3640 	 * full residue, then set eof back  to ST_EOM to make sure that
3641 	 * the user will see at least one zero write
3642 	 * after this short write
3643 	 */
3644 	mutex_enter(ST_MUTEX);
3645 	if (un->un_pos.eof > ST_NO_EOF) {
3646 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3647 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3648 	}
3649 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3650 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3651 			un->un_pos.eof = ST_EOM;
3652 		} else if (uio->uio_resid == len) {
3653 			un->un_pos.eof = ST_NO_EOF;
3654 		}
3655 	}
3656 
3657 	if (un->un_silent_skip && uio->uio_resid != len) {
3658 		un->un_pos.eof = ST_EOF;
3659 		un->un_pos.blkno = un->un_save_blkno;
3660 		un->un_pos.fileno--;
3661 	}
3662 
3663 	un->un_errno = rval;
3664 
3665 	mutex_exit(ST_MUTEX);
3666 
3667 	return (rval);
3668 }
3669 
3670 static int
3671 st_arw(dev_t dev, struct aio_req *aio, int flag)
3672 {
3673 	struct uio *uio = aio->aio_uio;
3674 	int rval = 0;
3675 	long len;
3676 
3677 	GET_SOFT_STATE(dev);
3678 
3679 	ST_FUNC(ST_DEVINFO, st_arw);
3680 
3681 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3682 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3683 	    (flag == B_READ ? rd_str: wr_str));
3684 
3685 	/* get local copy of transfer length */
3686 	len = uio->uio_iov->iov_len;
3687 
3688 	mutex_enter(ST_MUTEX);
3689 
3690 	/*
3691 	 * If in fixed block size mode and requested read or write
3692 	 * is not an even multiple of that block size.
3693 	 */
3694 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3695 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3696 		    "%s: not modulo %d block size\n",
3697 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3698 		rval = EINVAL;
3699 	}
3700 
3701 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3702 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3703 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3704 		    "%s: not modulo %d device granularity\n",
3705 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3706 		rval = EINVAL;
3707 	}
3708 
3709 	if (rval != 0) {
3710 		un->un_errno = rval;
3711 		mutex_exit(ST_MUTEX);
3712 		return (rval);
3713 	}
3714 
3715 	mutex_exit(ST_MUTEX);
3716 
3717 	len = uio->uio_resid;
3718 
3719 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3720 
3721 	/*
3722 	 * if we have hit logical EOT during this xfer and there is not a
3723 	 * full residue, then set eof back  to ST_EOM to make sure that
3724 	 * the user will see at least one zero write
3725 	 * after this short write
3726 	 *
3727 	 * we keep this here just in case the application is not using
3728 	 * persistent errors
3729 	 */
3730 	mutex_enter(ST_MUTEX);
3731 	if (un->un_pos.eof > ST_NO_EOF) {
3732 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3733 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3734 	}
3735 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3736 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3737 			un->un_pos.eof = ST_EOM;
3738 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3739 			un->un_pos.eof = ST_NO_EOF;
3740 		}
3741 	}
3742 	un->un_errno = rval;
3743 	mutex_exit(ST_MUTEX);
3744 
3745 	return (rval);
3746 }
3747 
3748 
3749 
3750 static int
3751 st_strategy(struct buf *bp)
3752 {
3753 	struct scsi_tape *un;
3754 	dev_t dev = bp->b_edev;
3755 
3756 	/*
3757 	 * validate arguments
3758 	 */
3759 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3760 		bp->b_resid = bp->b_bcount;
3761 		mutex_enter(ST_MUTEX);
3762 		st_bioerror(bp, ENXIO);
3763 		mutex_exit(ST_MUTEX);
3764 		goto error;
3765 	}
3766 
3767 	ST_ENTR(ST_DEVINFO, st_strategy);
3768 
3769 	mutex_enter(ST_MUTEX);
3770 
3771 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3772 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3773 	}
3774 
3775 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3776 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3777 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3778 
3779 	/*
3780 	 * If persistent errors have been flagged, just nix this one. We wait
3781 	 * for any outstanding I/O's below, so we will be in order.
3782 	 */
3783 	if (IS_PE_FLAG_SET(un)) {
3784 		goto exit;
3785 	}
3786 
3787 	if (bp != un->un_sbufp) {
3788 		char reading = bp->b_flags & B_READ;
3789 		int wasopening = 0;
3790 
3791 		/*
3792 		 * If we haven't done/checked reservation on the tape unit
3793 		 * do it now.
3794 		 */
3795 		if ((un->un_rsvd_status &
3796 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
3797 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
3798 				if (st_reserve_release(un, ST_RESERVE)) {
3799 					st_bioerror(bp, un->un_errno);
3800 					goto exit;
3801 				}
3802 			} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3803 				/*
3804 				 * Enter here to restore position for possible
3805 				 * resets when the device was closed and opened
3806 				 * in O_NDELAY mode subsequently
3807 				 */
3808 				un->un_state = ST_STATE_INITIALIZING;
3809 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3810 				    0, SYNC_CMD);
3811 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3812 			}
3813 			un->un_rsvd_status |= ST_INIT_RESERVE;
3814 		}
3815 
3816 		/*
3817 		 * If we are offline, we have to initialize everything first.
3818 		 * This is to handle either when opened with O_NDELAY, or
3819 		 * we just got a new tape in the drive, after an offline.
3820 		 * We don't observe O_NDELAY past the open,
3821 		 * as it will not make sense for tapes.
3822 		 */
3823 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3824 			/* reset state to avoid recursion */
3825 			un->un_state = ST_STATE_INITIALIZING;
3826 			if (st_tape_init(dev)) {
3827 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3828 				    "stioctl : OFFLINE init failure ");
3829 				un->un_state = ST_STATE_OFFLINE;
3830 				un->un_pos.pmode = invalid;
3831 				goto b_done_err;
3832 			}
3833 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3834 		}
3835 		/*
3836 		 * Check for legal operations
3837 		 */
3838 		if (un->un_pos.pmode == invalid) {
3839 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3840 			    "strategy with un->un_pos.pmode invalid\n");
3841 			goto b_done_err;
3842 		}
3843 
3844 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3845 		    "st_strategy(): regular io\n");
3846 
3847 		/*
3848 		 * Process this first. If we were reading, and we're pending
3849 		 * logical eot, that means we've bumped one file mark too far.
3850 		 */
3851 
3852 		/*
3853 		 * Recursion warning: st_cmd will route back through here.
3854 		 */
3855 		if (un->un_pos.eof == ST_EOT_PENDING) {
3856 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3857 				un->un_pos.pmode = invalid;
3858 				un->un_density_known = 0;
3859 				goto b_done_err;
3860 			}
3861 			un->un_pos.blkno = 0; /* fix up block number.. */
3862 			un->un_pos.eof = ST_EOT;
3863 		}
3864 
3865 		/*
3866 		 * If we are in the process of opening, we may have to
3867 		 * determine/set the correct density. We also may have
3868 		 * to do a test_append (if QIC) to see whether we are
3869 		 * in a position to append to the end of the tape.
3870 		 *
3871 		 * If we're already at logical eot, we transition
3872 		 * to ST_NO_EOF. If we're at physical eot, we punt
3873 		 * to the switch statement below to handle.
3874 		 */
3875 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3876 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3877 
3878 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3879 				if (st_determine_density(dev, (int)reading)) {
3880 					goto b_done_err;
3881 				}
3882 			}
3883 
3884 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3885 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3886 			    un->un_pos.fileno, (int)reading,
3887 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3888 			    un->un_pos.eof);
3889 
3890 			if (!reading && un->un_pos.eof != ST_EOM) {
3891 				if (un->un_pos.eof == ST_EOT) {
3892 					un->un_pos.eof = ST_NO_EOF;
3893 				} else if (un->un_pos.pmode != invalid &&
3894 				    (un->un_dp->options & ST_QIC)) {
3895 					/*
3896 					 * st_test_append() will do it all
3897 					 */
3898 					st_test_append(bp);
3899 					goto done;
3900 				}
3901 			}
3902 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3903 				wasopening = 1;
3904 			}
3905 			un->un_laststate = un->un_state;
3906 			un->un_state = ST_STATE_OPEN;
3907 		}
3908 
3909 
3910 		/*
3911 		 * Process rest of END OF FILE and END OF TAPE conditions
3912 		 */
3913 
3914 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3915 		    "eof=%x, wasopening=%x\n",
3916 		    un->un_pos.eof, wasopening);
3917 
3918 		switch (un->un_pos.eof) {
3919 		case ST_EOM:
3920 			/*
3921 			 * This allows writes to proceed past physical
3922 			 * eot. We'll *really* be in trouble if the
3923 			 * user continues blindly writing data too
3924 			 * much past this point (unwind the tape).
3925 			 * Physical eot really means 'early warning
3926 			 * eot' in this context.
3927 			 *
3928 			 * Every other write from now on will succeed
3929 			 * (if sufficient  tape left).
3930 			 * This write will return with resid == count
3931 			 * but the next one should be successful
3932 			 *
3933 			 * Note that we only transition to logical EOT
3934 			 * if the last state wasn't the OPENING state.
3935 			 * We explicitly prohibit running up to physical
3936 			 * eot, closing the device, and then re-opening
3937 			 * to proceed. Trailer records may only be gotten
3938 			 * at by keeping the tape open after hitting eot.
3939 			 *
3940 			 * Also note that ST_EOM cannot be set by reading-
3941 			 * this can only be set during writing. Reading
3942 			 * up to the end of the tape gets a blank check
3943 			 * or a double-filemark indication (ST_EOT_PENDING),
3944 			 * and we prohibit reading after that point.
3945 			 *
3946 			 */
3947 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
3948 			if (wasopening == 0) {
3949 				/*
3950 				 * this allows st_rw() to reset it back to
3951 				 * ST_EOM to make sure that the application
3952 				 * will see a zero write
3953 				 */
3954 				un->un_pos.eof = ST_WRITE_AFTER_EOM;
3955 			}
3956 			un->un_status = SUN_KEY_EOT;
3957 			goto b_done;
3958 
3959 		case ST_WRITE_AFTER_EOM:
3960 		case ST_EOT:
3961 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
3962 			un->un_status = SUN_KEY_EOT;
3963 			if (SVR4_BEHAVIOR && reading) {
3964 				goto b_done_err;
3965 			}
3966 
3967 			if (reading) {
3968 				goto b_done;
3969 			}
3970 			un->un_pos.eof = ST_NO_EOF;
3971 			break;
3972 
3973 		case ST_EOF_PENDING:
3974 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3975 			    "EOF PENDING\n");
3976 			un->un_status = SUN_KEY_EOF;
3977 			if (SVR4_BEHAVIOR) {
3978 				un->un_pos.eof = ST_EOF;
3979 				goto b_done;
3980 			}
3981 			/* FALLTHROUGH */
3982 		case ST_EOF:
3983 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
3984 			un->un_status = SUN_KEY_EOF;
3985 			if (SVR4_BEHAVIOR) {
3986 				goto b_done_err;
3987 			}
3988 
3989 			if (BSD_BEHAVIOR) {
3990 				un->un_pos.eof = ST_NO_EOF;
3991 				un->un_pos.fileno += 1;
3992 				un->un_pos.blkno   = 0;
3993 			}
3994 
3995 			if (reading) {
3996 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3997 				    "now file %d (read)\n",
3998 				    un->un_pos.fileno);
3999 				goto b_done;
4000 			}
4001 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4002 			    "now file %d (write)\n", un->un_pos.fileno);
4003 			break;
4004 		default:
4005 			un->un_status = 0;
4006 			break;
4007 		}
4008 	}
4009 
4010 	bp->b_flags &= ~(B_DONE);
4011 	st_bioerror(bp, 0);
4012 	bp->av_forw = NULL;
4013 	bp->b_resid = 0;
4014 	SET_BP_PKT(bp, 0);
4015 
4016 
4017 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4018 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4019 	    " pkt=0x%p\n",
4020 	    (void *)bp->b_forw, bp->b_bcount,
4021 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4022 
4023 #ifdef	__x86
4024 	/*
4025 	 * We will replace bp with a new bp that can do big blk xfer
4026 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4027 	 *
4028 	 * Also, we need to make sure that we're handling real I/O
4029 	 * by checking group 0/1 SCSI I/O commands, if needed
4030 	 */
4031 	if (bp->b_bcount > un->un_maxdma_arch &&
4032 	    (bp != un->un_sbufp					||
4033 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ		||
4034 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G1	||
4035 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE	||
4036 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G1)) {
4037 		mutex_exit(ST_MUTEX);
4038 		bp = st_get_bigblk_bp(bp);
4039 		mutex_enter(ST_MUTEX);
4040 	}
4041 #endif
4042 
4043 	/* put on wait queue */
4044 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4045 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4046 	    (void *)un->un_quef, (void *)bp);
4047 
4048 	if (un->un_quef) {
4049 		un->un_quel->b_actf = bp;
4050 	} else {
4051 		un->un_quef = bp;
4052 	}
4053 	un->un_quel = bp;
4054 
4055 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4056 
4057 	st_start(un);
4058 
4059 done:
4060 	mutex_exit(ST_MUTEX);
4061 	return (0);
4062 
4063 
4064 error:
4065 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4066 	    "st_strategy: error exit\n");
4067 
4068 	biodone(bp);
4069 	return (0);
4070 
4071 b_done_err:
4072 	st_bioerror(bp, EIO);
4073 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4074 	    "st_strategy : EIO b_done_err\n");
4075 
4076 b_done:
4077 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4078 	    "st_strategy: b_done\n");
4079 
4080 exit:
4081 	/*
4082 	 * make sure no commands are outstanding or waiting before closing,
4083 	 * so we can guarantee order
4084 	 */
4085 	st_wait_for_io(un);
4086 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4087 
4088 	/* override errno here, if persistent errors were flagged */
4089 	if (IS_PE_FLAG_SET(un))
4090 		bioerror(bp, un->un_errno);
4091 
4092 	mutex_exit(ST_MUTEX);
4093 
4094 	biodone(bp);
4095 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4096 	return (0);
4097 }
4098 
4099 
4100 
4101 /*
4102  * this routine spaces forward over filemarks
4103  */
4104 static int
4105 st_space_fmks(dev_t dev, int count)
4106 {
4107 	int rval = 0;
4108 
4109 	GET_SOFT_STATE(dev);
4110 
4111 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4112 
4113 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4114 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
4115 
4116 	ASSERT(mutex_owned(ST_MUTEX));
4117 
4118 	/*
4119 	 * the risk with doing only one space operation is that we
4120 	 * may accidentily jump in old data
4121 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4122 	 * because the 8200 does not append a marker; in order not to
4123 	 * sacrifice the fast file skip, we do a slow skip if the low
4124 	 * density device has been opened
4125 	 */
4126 
4127 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4128 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
4129 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4130 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4131 			    "space_fmks : EIO can't do space cmd #1\n");
4132 			rval = EIO;
4133 		}
4134 	} else {
4135 		while (count > 0) {
4136 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4137 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4138 				    "space_fmks : EIO can't do space cmd #2\n");
4139 				rval = EIO;
4140 				break;
4141 			}
4142 			count -= 1;
4143 			/*
4144 			 * read a block to see if we have reached
4145 			 * end of medium (double filemark for reel or
4146 			 * medium error for others)
4147 			 */
4148 			if (count > 0) {
4149 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
4150 				    SYNC_CMD)) {
4151 					ST_DEBUG2(ST_DEVINFO, st_label,
4152 					    SCSI_DEBUG,
4153 					    "space_fmks : EIO can't do "
4154 					    "space cmd #3\n");
4155 					rval = EIO;
4156 					break;
4157 				}
4158 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4159 				    (un->un_dp->options & ST_REEL)) {
4160 					un->un_status = SUN_KEY_EOT;
4161 					ST_DEBUG2(ST_DEVINFO, st_label,
4162 					    SCSI_DEBUG,
4163 					    "space_fmks : EIO ST_REEL\n");
4164 					rval = EIO;
4165 					break;
4166 				} else if (IN_EOF(un->un_pos)) {
4167 					un->un_pos.eof = ST_NO_EOF;
4168 					un->un_pos.fileno++;
4169 					un->un_pos.blkno = 0;
4170 					count--;
4171 				} else if (un->un_pos.eof > ST_EOF) {
4172 					ST_DEBUG2(ST_DEVINFO, st_label,
4173 					    SCSI_DEBUG,
4174 					    "space_fmks, EIO > ST_EOF\n");
4175 					rval = EIO;
4176 					break;
4177 				}
4178 
4179 			}
4180 		}
4181 		un->un_err_resid = count;
4182 		COPY_POS(&un->un_pos, &un->un_err_pos);
4183 	}
4184 	ASSERT(mutex_owned(ST_MUTEX));
4185 	return (rval);
4186 }
4187 
4188 /*
4189  * this routine spaces to EOD
4190  *
4191  * it keeps track of the current filenumber and returns the filenumber after
4192  * the last successful space operation, we keep the number high because as
4193  * tapes are getting larger, the possibility of more and more files exist,
4194  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4195  * soon
4196  */
4197 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4198 
4199 static int
4200 st_find_eod(dev_t dev)
4201 {
4202 	tapepos_t savepos;
4203 	int sp_type;
4204 	struct scsi_tape *un;
4205 	int instance;
4206 	int result;
4207 
4208 	instance = MTUNIT(dev);
4209 	un = ddi_get_soft_state(st_state, instance);
4210 	if (un == NULL) {
4211 		return (-1);
4212 	}
4213 
4214 	ST_FUNC(ST_DEVINFO, st_find_eod);
4215 
4216 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4217 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", dev, un->un_pos.fileno);
4218 
4219 	ASSERT(mutex_owned(ST_MUTEX));
4220 
4221 	COPY_POS(&savepos, &un->un_pos);
4222 
4223 	/*
4224 	 * see if the drive is smart enough to do the skips in
4225 	 * one operation; 1/2" use two filemarks
4226 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4227 	 * because the 8200 does not append a marker; in order not to
4228 	 * sacrifice the fast file skip, we do a slow skip if the low
4229 	 * density device has been opened
4230 	 */
4231 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4232 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4233 		    (MT_DENSITY(dev) == 0)) {
4234 			sp_type = Fmk(1);
4235 		} else if (un->un_pos.pmode == logical) {
4236 			sp_type = SPACE(SP_EOD, 0);
4237 		} else {
4238 			sp_type = Fmk(MAX_SKIP);
4239 		}
4240 	} else {
4241 		sp_type = Fmk(1);
4242 	}
4243 
4244 	for (;;) {
4245 		result = st_cmd(dev, SCMD_SPACE, sp_type, SYNC_CMD);
4246 
4247 		if (result == 0) {
4248 			COPY_POS(&savepos, &un->un_pos);
4249 		}
4250 
4251 		if (sp_type == SPACE(SP_EOD, 0)) {
4252 			if (result != 0) {
4253 				sp_type = Fmk(MAX_SKIP);
4254 				continue;
4255 			}
4256 
4257 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4258 			    "st_find_eod: 0x%"PRIx64"\n",
4259 			    savepos.lgclblkno);
4260 			/*
4261 			 * What we return will become the current file position.
4262 			 * After completing the space command with the position
4263 			 * mode that is not invalid a read position command will
4264 			 * be automaticly issued. If the drive support the long
4265 			 * read position format a valid file position can be
4266 			 * returned.
4267 			 */
4268 			return (un->un_pos.fileno);
4269 		}
4270 
4271 		if (result != 0) {
4272 			break;
4273 		}
4274 
4275 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4276 		    "count=%x, eof=%x, status=%x\n",
4277 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4278 
4279 		/*
4280 		 * If we're not EOM smart,  space a record
4281 		 * to see whether we're now in the slot between
4282 		 * the two sequential filemarks that logical
4283 		 * EOM consists of (REEL) or hit nowhere land
4284 		 * (8mm).
4285 		 */
4286 		if (sp_type == Fmk(1)) {
4287 			/*
4288 			 * no fast skipping, check a record
4289 			 */
4290 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4291 				break;
4292 			}
4293 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4294 			    (un->un_dp->options & ST_REEL)) {
4295 				un->un_status = KEY_BLANK_CHECK;
4296 				un->un_pos.fileno++;
4297 				un->un_pos.blkno = 0;
4298 				break;
4299 			}
4300 			if (IN_EOF(un->un_pos)) {
4301 				un->un_pos.eof = ST_NO_EOF;
4302 				un->un_pos.fileno++;
4303 				un->un_pos.blkno = 0;
4304 			}
4305 			if (un->un_pos.eof > ST_EOF) {
4306 				break;
4307 			}
4308 		} else {
4309 			if (un->un_pos.eof > ST_EOF) {
4310 				break;
4311 			}
4312 		}
4313 	}
4314 
4315 	if (un->un_dp->options & ST_KNOWS_EOD) {
4316 		COPY_POS(&savepos, &un->un_pos);
4317 	}
4318 
4319 	ASSERT(mutex_owned(ST_MUTEX));
4320 
4321 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4322 	    "st_find_eod: %x\n", savepos.fileno);
4323 	return (savepos.fileno);
4324 }
4325 
4326 
4327 /*
4328  * this routine is frequently used in ioctls below;
4329  * it determines whether we know the density and if not will
4330  * determine it
4331  * if we have written the tape before, one or more filemarks are written
4332  *
4333  * depending on the stepflag, the head is repositioned to where it was before
4334  * the filemarks were written in order not to confuse step counts
4335  */
4336 #define	STEPBACK    0
4337 #define	NO_STEPBACK 1
4338 
4339 static int
4340 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4341 {
4342 
4343 	GET_SOFT_STATE(dev);
4344 
4345 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4346 
4347 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4348 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4349 	    "\n", dev, wfm, mode, stepflag);
4350 
4351 	ASSERT(mutex_owned(ST_MUTEX));
4352 
4353 	/*
4354 	 * If we don't yet know the density of the tape we have inserted,
4355 	 * we have to either unconditionally set it (if we're 'writing'),
4356 	 * or we have to determine it. As side effects, check for any
4357 	 * write-protect errors, and for the need to put out any file-marks
4358 	 * before positioning a tape.
4359 	 *
4360 	 * If we are going to be spacing forward, and we haven't determined
4361 	 * the tape density yet, we have to do so now...
4362 	 */
4363 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4364 		if (st_determine_density(dev, mode)) {
4365 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4366 			    "check_density_or_wfm : EIO can't determine "
4367 			    "density\n");
4368 			un->un_errno = EIO;
4369 			return (EIO);
4370 		}
4371 		/*
4372 		 * Presumably we are at BOT. If we attempt to write, it will
4373 		 * either work okay, or bomb. We don't do a st_test_append
4374 		 * unless we're past BOT.
4375 		 */
4376 		un->un_laststate = un->un_state;
4377 		un->un_state = ST_STATE_OPEN;
4378 
4379 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4380 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4381 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4382 
4383 		tapepos_t spos;
4384 
4385 		COPY_POS(&spos, &un->un_pos);
4386 
4387 		/*
4388 		 * We need to write one or two filemarks.
4389 		 * In the case of the HP, we need to
4390 		 * position the head between the two
4391 		 * marks.
4392 		 */
4393 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4394 			wfm = un->un_fmneeded;
4395 			un->un_fmneeded = 0;
4396 		}
4397 
4398 		if (st_write_fm(dev, wfm)) {
4399 			un->un_pos.pmode = invalid;
4400 			un->un_density_known = 0;
4401 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4402 			    "check_density_or_wfm : EIO can't write fm\n");
4403 			un->un_errno = EIO;
4404 			return (EIO);
4405 		}
4406 
4407 		if (stepflag == STEPBACK) {
4408 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
4409 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4410 				    "check_density_or_wfm : EIO can't space "
4411 				    "(-wfm)\n");
4412 				un->un_errno = EIO;
4413 				return (EIO);
4414 			}
4415 			COPY_POS(&un->un_pos, &spos);
4416 		}
4417 	}
4418 
4419 	/*
4420 	 * Whatever we do at this point clears the state of the eof flag.
4421 	 */
4422 
4423 	un->un_pos.eof = ST_NO_EOF;
4424 
4425 	/*
4426 	 * If writing, let's check that we're positioned correctly
4427 	 * at the end of tape before issuing the next write.
4428 	 */
4429 	if (un->un_read_only == RDWR) {
4430 		un->un_test_append = 1;
4431 	}
4432 
4433 	ASSERT(mutex_owned(ST_MUTEX));
4434 	return (0);
4435 }
4436 
4437 
4438 /*
4439  * Wait for all outstaning I/O's to complete
4440  *
4441  * we wait on both ncmds and the wait queue for times when we are flushing
4442  * after persistent errors are flagged, which is when ncmds can be 0, and the
4443  * queue can still have I/O's.  This way we preserve order of biodone's.
4444  */
4445 static void
4446 st_wait_for_io(struct scsi_tape *un)
4447 {
4448 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4449 	ASSERT(mutex_owned(ST_MUTEX));
4450 	while (un->un_ncmds && un->un_quef) { /* XXX fix for async write@EOM */
4451 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4452 	}
4453 }
4454 
4455 /*
4456  * This routine implements the ioctl calls.  It is called
4457  * from the device switch at normal priority.
4458  */
4459 /*ARGSUSED*/
4460 static int
4461 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4462     int *rval_p)
4463 {
4464 	int tmp, rval = 0;
4465 
4466 	GET_SOFT_STATE(dev);
4467 
4468 	ST_ENTR(ST_DEVINFO, st_ioctl);
4469 
4470 	mutex_enter(ST_MUTEX);
4471 
4472 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4473 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4474 	    "pe_flag = %d\n",
4475 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4476 	    IS_PE_FLAG_SET(un));
4477 
4478 	/*
4479 	 * We don't want to block on these, so let them through
4480 	 * and we don't care about setting driver states here.
4481 	 */
4482 	if ((cmd == MTIOCGETDRIVETYPE) ||
4483 	    (cmd == MTIOCGUARANTEEDORDER) ||
4484 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4485 		goto check_commands;
4486 	}
4487 
4488 	/*
4489 	 * We clear error entry stack except command
4490 	 * MTIOCGETERROR and MTIOCGET
4491 	 */
4492 	if ((cmd != MTIOCGETERROR) &&
4493 	    (cmd != MTIOCGET)) {
4494 		st_empty_error_stack(un);
4495 	}
4496 
4497 	/*
4498 	 * wait for all outstanding commands to complete, or be dequeued.
4499 	 * And because ioctl's are synchronous commands, any return value
4500 	 * after this,  will be in order
4501 	 */
4502 	st_wait_for_io(un);
4503 
4504 	/*
4505 	 * allow only a through clear errors and persistent status, and
4506 	 * status
4507 	 */
4508 	if (IS_PE_FLAG_SET(un)) {
4509 		if ((cmd == MTIOCLRERR) ||
4510 		    (cmd == MTIOCPERSISTENT) ||
4511 		    (cmd == MTIOCGET)) {
4512 			goto check_commands;
4513 		} else {
4514 			rval = un->un_errno;
4515 			goto exit;
4516 		}
4517 	}
4518 
4519 	un->un_throttle = 1;	/* > 1 will never happen here */
4520 	un->un_errno = 0;	/* start clean from here */
4521 
4522 	/*
4523 	 * first and foremost, handle any ST_EOT_PENDING cases.
4524 	 * That is, if a logical eot is pending notice, notice it.
4525 	 */
4526 	if (un->un_pos.eof == ST_EOT_PENDING) {
4527 		int resid = un->un_err_resid;
4528 		uchar_t status = un->un_status;
4529 		uchar_t lastop = un->un_lastop;
4530 
4531 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
4532 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4533 			    "stioctl : EIO can't space fmk(-1)\n");
4534 			rval = EIO;
4535 			goto exit;
4536 		}
4537 		un->un_lastop = lastop; /* restore last operation */
4538 		if (status == SUN_KEY_EOF) {
4539 			un->un_status = SUN_KEY_EOT;
4540 		} else {
4541 			un->un_status = status;
4542 		}
4543 		un->un_err_resid  = resid;
4544 		/* fix up block number */
4545 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4546 		/* now we're at logical eot */
4547 		un->un_pos.eof = ST_EOT;
4548 	}
4549 
4550 	/*
4551 	 * now, handle the rest of the situations
4552 	 */
4553 check_commands:
4554 	switch (cmd) {
4555 	case MTIOCGET:
4556 	{
4557 #ifdef _MULTI_DATAMODEL
4558 		/*
4559 		 * For use when a 32 bit app makes a call into a
4560 		 * 64 bit ioctl
4561 		 */
4562 		struct mtget32		mtg_local32;
4563 		struct mtget32 		*mtget_32 = &mtg_local32;
4564 #endif /* _MULTI_DATAMODEL */
4565 
4566 			/* Get tape status */
4567 		struct mtget mtg_local;
4568 		struct mtget *mtget = &mtg_local;
4569 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4570 		    "st_ioctl: MTIOCGET\n");
4571 
4572 		bzero((caddr_t)mtget, sizeof (struct mtget));
4573 		mtget->mt_erreg = un->un_status;
4574 		mtget->mt_resid = un->un_err_resid;
4575 		mtget->mt_dsreg = un->un_retry_ct;
4576 		if (un->un_err_pos.pmode == legacy) {
4577 			mtget->mt_fileno = un->un_err_pos.fileno;
4578 		} else {
4579 			mtget->mt_fileno = -1;
4580 		}
4581 		mtget->mt_blkno = un->un_err_pos.blkno;
4582 		mtget->mt_type = un->un_dp->type;
4583 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4584 		if (un->un_read_pos_type != NO_POS) {
4585 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4586 		}
4587 		if (un->un_dp->options & ST_REEL) {
4588 			mtget->mt_flags |= MTF_REEL;
4589 			mtget->mt_bf = 20;
4590 		} else {		/* 1/4" cartridges */
4591 			switch (mtget->mt_type) {
4592 			/* Emulex cartridge tape */
4593 			case MT_ISMT02:
4594 				mtget->mt_bf = 40;
4595 				break;
4596 			default:
4597 				mtget->mt_bf = 126;
4598 				break;
4599 			}
4600 		}
4601 
4602 		/*
4603 		 * If large transfers are allowed and drive options
4604 		 * has no record size limit set. Calculate blocking
4605 		 * factor from the lesser of maxbsize and maxdma.
4606 		 */
4607 		if ((un->un_allow_large_xfer) &&
4608 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4609 			mtget->mt_bf = min(un->un_maxbsize,
4610 			    un->un_maxdma) / SECSIZE;
4611 		}
4612 
4613 			if (un->un_read_only == WORM ||
4614 			    un->un_read_only == RDWORM) {
4615 				mtget->mt_flags |= MTF_WORM_MEDIA;
4616 			}
4617 
4618 			rval = st_check_clean_bit(dev);
4619 			if (rval == -1) {
4620 				rval = EIO;
4621 				goto exit;
4622 			} else {
4623 				mtget->mt_flags |= (ushort_t)rval;
4624 				rval = 0;
4625 			}
4626 
4627 		un->un_status = 0;		/* Reset status */
4628 		un->un_err_resid = 0;
4629 		tmp = sizeof (struct mtget);
4630 
4631 #ifdef _MULTI_DATAMODEL
4632 
4633 		switch (ddi_model_convert_from(flag & FMODELS)) {
4634 		case DDI_MODEL_ILP32:
4635 			/*
4636 			 * Convert 64 bit back to 32 bit before doing
4637 			 * copyout. This is what the ILP32 app expects.
4638 			 */
4639 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4640 			mtget_32->mt_resid = 	mtget->mt_resid;
4641 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4642 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4643 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4644 			mtget_32->mt_type =  	mtget->mt_type;
4645 			mtget_32->mt_flags = 	mtget->mt_flags;
4646 			mtget_32->mt_bf = 	mtget->mt_bf;
4647 
4648 			if (ddi_copyout(mtget_32, (void *)arg,
4649 			    sizeof (struct mtget32), flag)) {
4650 				rval = EFAULT;
4651 			}
4652 			break;
4653 
4654 		case DDI_MODEL_NONE:
4655 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4656 				rval = EFAULT;
4657 			}
4658 			break;
4659 		}
4660 #else /* ! _MULTI_DATAMODE */
4661 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4662 			rval = EFAULT;
4663 		}
4664 #endif /* _MULTI_DATAMODE */
4665 
4666 		break;
4667 	}
4668 	case MTIOCGETERROR:
4669 			/*
4670 			 * get error entry from error stack
4671 			 */
4672 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4673 			    "st_ioctl: MTIOCGETERROR\n");
4674 
4675 			rval = st_get_error_entry(un, arg, flag);
4676 
4677 			break;
4678 
4679 	case MTIOCSTATE:
4680 		{
4681 			/*
4682 			 * return when media presence matches state
4683 			 */
4684 			enum mtio_state state;
4685 
4686 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4687 			    "st_ioctl: MTIOCSTATE\n");
4688 
4689 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4690 				rval = EFAULT;
4691 
4692 			mutex_exit(ST_MUTEX);
4693 
4694 			rval = st_check_media(dev, state);
4695 
4696 			mutex_enter(ST_MUTEX);
4697 
4698 			if (rval != 0) {
4699 				break;
4700 			}
4701 
4702 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4703 			    sizeof (int), flag))
4704 				rval = EFAULT;
4705 			break;
4706 
4707 		}
4708 
4709 	case MTIOCGETDRIVETYPE:
4710 		{
4711 #ifdef _MULTI_DATAMODEL
4712 		/*
4713 		 * For use when a 32 bit app makes a call into a
4714 		 * 64 bit ioctl
4715 		 */
4716 		struct mtdrivetype_request32	mtdtrq32;
4717 #endif /* _MULTI_DATAMODEL */
4718 
4719 			/*
4720 			 * return mtdrivetype
4721 			 */
4722 			struct mtdrivetype_request mtdtrq;
4723 			struct mtdrivetype mtdrtyp;
4724 			struct mtdrivetype *mtdt = &mtdrtyp;
4725 			struct st_drivetype *stdt = un->un_dp;
4726 
4727 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4728 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
4729 
4730 #ifdef _MULTI_DATAMODEL
4731 		switch (ddi_model_convert_from(flag & FMODELS)) {
4732 		case DDI_MODEL_ILP32:
4733 		{
4734 			if (ddi_copyin((void *)arg, &mtdtrq32,
4735 			    sizeof (struct mtdrivetype_request32), flag)) {
4736 				rval = EFAULT;
4737 				break;
4738 			}
4739 			mtdtrq.size = mtdtrq32.size;
4740 			mtdtrq.mtdtp =
4741 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
4742 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4743 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
4744 			break;
4745 		}
4746 		case DDI_MODEL_NONE:
4747 			if (ddi_copyin((void *)arg, &mtdtrq,
4748 			    sizeof (struct mtdrivetype_request), flag)) {
4749 				rval = EFAULT;
4750 				break;
4751 			}
4752 			break;
4753 		}
4754 
4755 #else /* ! _MULTI_DATAMODEL */
4756 		if (ddi_copyin((void *)arg, &mtdtrq,
4757 		    sizeof (struct mtdrivetype_request), flag)) {
4758 			rval = EFAULT;
4759 			break;
4760 		}
4761 #endif /* _MULTI_DATAMODEL */
4762 
4763 			/*
4764 			 * if requested size is < 0 then return
4765 			 * error.
4766 			 */
4767 			if (mtdtrq.size < 0) {
4768 				rval = EINVAL;
4769 				break;
4770 			}
4771 			bzero(mtdt, sizeof (struct mtdrivetype));
4772 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
4773 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
4774 			mtdt->type = stdt->type;
4775 			mtdt->bsize = stdt->bsize;
4776 			mtdt->options = stdt->options;
4777 			mtdt->max_rretries = stdt->max_rretries;
4778 			mtdt->max_wretries = stdt->max_wretries;
4779 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4780 				mtdt->densities[tmp] = stdt->densities[tmp];
4781 			}
4782 			mtdt->default_density = stdt->default_density;
4783 			/*
4784 			 * Speed hasn't been used since the hayday of reel tape.
4785 			 * For all drives not setting the option ST_KNOWS_MEDIA
4786 			 * the speed member renamed to mediatype are zeros.
4787 			 * Those drives that have ST_KNOWS_MEDIA set use the
4788 			 * new mediatype member which is used to figure the
4789 			 * type of media loaded.
4790 			 *
4791 			 * So as to not break applications speed in the
4792 			 * mtdrivetype structure is not renamed.
4793 			 */
4794 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4795 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4796 			}
4797 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4798 			mtdt->io_timeout = stdt->io_timeout;
4799 			mtdt->rewind_timeout = stdt->rewind_timeout;
4800 			mtdt->space_timeout = stdt->space_timeout;
4801 			mtdt->load_timeout = stdt->load_timeout;
4802 			mtdt->unload_timeout = stdt->unload_timeout;
4803 			mtdt->erase_timeout = stdt->erase_timeout;
4804 
4805 			/*
4806 			 * Limit the maximum length of the result to
4807 			 * sizeof (struct mtdrivetype).
4808 			 */
4809 			tmp = sizeof (struct mtdrivetype);
4810 			if (mtdtrq.size < tmp)
4811 				tmp = mtdtrq.size;
4812 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4813 				rval = EFAULT;
4814 			}
4815 			break;
4816 		}
4817 	case MTIOCPERSISTENT:
4818 		{
4819 			int persistence = 0;
4820 
4821 			if (ddi_copyin((void *)arg, &persistence,
4822 			    sizeof (int), flag)) {
4823 				rval = EFAULT;
4824 				break;
4825 			}
4826 
4827 			/* non zero sets it, only 0 turns it off */
4828 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4829 
4830 			if (un->un_persistence) {
4831 				TURN_PE_ON(un);
4832 			} else {
4833 				TURN_PE_OFF(un);
4834 			}
4835 
4836 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4837 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4838 			    un->un_persistence);
4839 
4840 			break;
4841 		}
4842 	case MTIOCPERSISTENTSTATUS:
4843 		{
4844 			int persistence = (int)un->un_persistence;
4845 
4846 			if (ddi_copyout(&persistence, (void *)arg,
4847 			    sizeof (int), flag)) {
4848 				rval = EFAULT;
4849 			}
4850 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4851 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4852 			    un->un_persistence);
4853 
4854 			break;
4855 		}
4856 
4857 
4858 	case MTIOCLRERR:
4859 		{
4860 			/* clear persistent errors */
4861 
4862 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4863 			    "st_ioctl: MTIOCLRERR\n");
4864 
4865 			CLEAR_PE(un);
4866 
4867 			break;
4868 		}
4869 
4870 	case MTIOCGUARANTEEDORDER:
4871 		{
4872 			/*
4873 			 * this is just a holder to make a valid ioctl and
4874 			 * it won't be in any earlier release
4875 			 */
4876 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4877 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4878 
4879 			break;
4880 		}
4881 
4882 	case MTIOCRESERVE:
4883 		{
4884 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4885 			    "st_ioctl: MTIOCRESERVE\n");
4886 
4887 			/*
4888 			 * Check if Reserve/Release is supported.
4889 			 */
4890 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4891 				rval = ENOTTY;
4892 				break;
4893 			}
4894 
4895 			rval = st_reserve_release(un, ST_RESERVE);
4896 
4897 			if (rval == 0) {
4898 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4899 			}
4900 			break;
4901 		}
4902 
4903 	case MTIOCRELEASE:
4904 		{
4905 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4906 			    "st_ioctl: MTIOCRELEASE\n");
4907 
4908 			/*
4909 			 * Check if Reserve/Release is supported.
4910 			 */
4911 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4912 				rval = ENOTTY;
4913 				break;
4914 			}
4915 
4916 			/*
4917 			 * Used to just clear ST_PRESERVE_RESERVE which
4918 			 * made the reservation release at next close.
4919 			 * As the user may have opened and then done a
4920 			 * persistant reservation we now need to drop
4921 			 * the reservation without closing if the user
4922 			 * attempts to do this.
4923 			 */
4924 			rval = st_reserve_release(un, ST_RELEASE);
4925 
4926 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
4927 
4928 			break;
4929 		}
4930 
4931 	case MTIOCFORCERESERVE:
4932 		{
4933 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4934 			    "st_ioctl: MTIOCFORCERESERVE\n");
4935 
4936 			/*
4937 			 * Check if Reserve/Release is supported.
4938 			 */
4939 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4940 				rval = ENOTTY;
4941 				break;
4942 			}
4943 			/*
4944 			 * allow only super user to run this.
4945 			 */
4946 			if (drv_priv(cred_p) != 0) {
4947 				rval = EPERM;
4948 				break;
4949 			}
4950 			/*
4951 			 * Throw away reserve,
4952 			 * not using test-unit-ready
4953 			 * since reserve can succeed without tape being
4954 			 * present in the drive.
4955 			 */
4956 			(void) st_reserve_release(un, ST_RESERVE);
4957 
4958 			rval = st_take_ownership(dev);
4959 
4960 			break;
4961 		}
4962 
4963 	case USCSICMD:
4964 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4965 		    "st_ioctl: USCSICMD\n");
4966 	{
4967 		cred_t	*cr;
4968 		cr = ddi_get_cred();
4969 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
4970 			rval = EPERM;
4971 		} else {
4972 			rval = st_ioctl_cmd(dev, (struct uscsi_cmd *)arg,
4973 			    flag);
4974 		}
4975 	}
4976 		break;
4977 
4978 	case MTIOCTOP:
4979 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4980 		    "st_ioctl: MTIOCTOP\n");
4981 		rval = st_mtioctop(un, arg, flag);
4982 		break;
4983 
4984 	case MTIOCLTOP:
4985 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4986 		    "st_ioctl: MTIOLCTOP\n");
4987 		rval = st_mtiocltop(un, arg, flag);
4988 		break;
4989 
4990 	case MTIOCREADIGNOREILI:
4991 		{
4992 			int set_ili;
4993 
4994 			if (ddi_copyin((void *)arg, &set_ili,
4995 			    sizeof (set_ili), flag)) {
4996 				rval = EFAULT;
4997 				break;
4998 			}
4999 
5000 			if (un->un_bsize) {
5001 				rval = ENOTTY;
5002 				break;
5003 			}
5004 
5005 			switch (set_ili) {
5006 			case 0:
5007 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5008 				break;
5009 
5010 			case 1:
5011 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5012 				break;
5013 
5014 			default:
5015 				rval = EINVAL;
5016 				break;
5017 			}
5018 			break;
5019 		}
5020 
5021 	case MTIOCREADIGNOREEOFS:
5022 		{
5023 			int ignore_eof;
5024 
5025 			if (ddi_copyin((void *)arg, &ignore_eof,
5026 			    sizeof (ignore_eof), flag)) {
5027 				rval = EFAULT;
5028 				break;
5029 			}
5030 
5031 			if (!(un->un_dp->options & ST_REEL)) {
5032 				rval = ENOTTY;
5033 				break;
5034 			}
5035 
5036 			switch (ignore_eof) {
5037 			case 0:
5038 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5039 				break;
5040 
5041 			case 1:
5042 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5043 				break;
5044 
5045 			default:
5046 				rval = EINVAL;
5047 				break;
5048 			}
5049 			break;
5050 		}
5051 
5052 	case MTIOCSHORTFMK:
5053 	{
5054 		int short_fmk;
5055 
5056 		if (ddi_copyin((void *)arg, &short_fmk,
5057 		    sizeof (short_fmk), flag)) {
5058 			rval = EFAULT;
5059 			break;
5060 		}
5061 
5062 		switch (un->un_dp->type) {
5063 		case ST_TYPE_EXB8500:
5064 		case ST_TYPE_EXABYTE:
5065 			if (!short_fmk) {
5066 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5067 			} else if (short_fmk == 1) {
5068 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5069 			} else {
5070 				rval = EINVAL;
5071 			}
5072 			break;
5073 
5074 		default:
5075 			rval = ENOTTY;
5076 			break;
5077 		}
5078 		break;
5079 	}
5080 
5081 	case MTIOCGETPOS:
5082 		rval = st_update_block_pos(un);
5083 		if (rval == 0) {
5084 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5085 			    sizeof (tapepos_t), flag)) {
5086 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5087 				    "MTIOCGETPOS copy out failed\n");
5088 				rval = EFAULT;
5089 			}
5090 		}
5091 		break;
5092 
5093 	case MTIOCRESTPOS:
5094 	{
5095 		tapepos_t dest;
5096 
5097 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5098 		    flag) != 0) {
5099 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5100 			    "MTIOCRESTPOS copy in failed\n");
5101 			rval = EFAULT;
5102 			break;
5103 		}
5104 		rval = st_validate_tapemarks(un, &dest);
5105 		if (rval != 0) {
5106 			rval = EIO;
5107 		}
5108 		break;
5109 	}
5110 	default:
5111 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5112 		    "st_ioctl: unknown ioctl\n");
5113 		rval = ENOTTY;
5114 	}
5115 
5116 exit:
5117 	if (!IS_PE_FLAG_SET(un)) {
5118 		un->un_errno = rval;
5119 	}
5120 
5121 	mutex_exit(ST_MUTEX);
5122 
5123 	return (rval);
5124 }
5125 
5126 
5127 /*
5128  * do some MTIOCTOP tape operations
5129  */
5130 static int
5131 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5132 {
5133 #ifdef _MULTI_DATAMODEL
5134 	/*
5135 	 * For use when a 32 bit app makes a call into a
5136 	 * 64 bit ioctl
5137 	 */
5138 	struct mtop32	mtop_32_for_64;
5139 #endif /* _MULTI_DATAMODEL */
5140 	struct mtop passed;
5141 	struct mtlop local;
5142 	int rval = 0;
5143 
5144 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5145 
5146 	ASSERT(mutex_owned(ST_MUTEX));
5147 
5148 #ifdef _MULTI_DATAMODEL
5149 	switch (ddi_model_convert_from(flag & FMODELS)) {
5150 	case DDI_MODEL_ILP32:
5151 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5152 		    sizeof (struct mtop32), flag)) {
5153 			return (EFAULT);
5154 		}
5155 		local.mt_op = mtop_32_for_64.mt_op;
5156 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5157 		break;
5158 
5159 	case DDI_MODEL_NONE:
5160 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5161 			return (EFAULT);
5162 		}
5163 		local.mt_op = passed.mt_op;
5164 		/* prevent sign extention */
5165 		local.mt_count = (UINT32_MAX & passed.mt_count);
5166 		break;
5167 	}
5168 
5169 #else /* ! _MULTI_DATAMODEL */
5170 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5171 		return (EFAULT);
5172 	}
5173 	local.mt_op = passed.mt_op;
5174 	/* prevent sign extention */
5175 	local.mt_count = (UINT32_MAX & passed.mt_count);
5176 #endif /* _MULTI_DATAMODEL */
5177 
5178 	rval = st_do_mtioctop(un, &local);
5179 
5180 #ifdef _MULTI_DATAMODEL
5181 	switch (ddi_model_convert_from(flag & FMODELS)) {
5182 	case DDI_MODEL_ILP32:
5183 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5184 			rval = ERANGE;
5185 			break;
5186 		}
5187 		/*
5188 		 * Convert 64 bit back to 32 bit before doing
5189 		 * copyout. This is what the ILP32 app expects.
5190 		 */
5191 		mtop_32_for_64.mt_op = local.mt_op;
5192 		mtop_32_for_64.mt_count = local.mt_count;
5193 
5194 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5195 		    sizeof (struct mtop32), flag)) {
5196 			rval = EFAULT;
5197 		}
5198 		break;
5199 
5200 	case DDI_MODEL_NONE:
5201 		passed.mt_count = local.mt_count;
5202 		passed.mt_op = local.mt_op;
5203 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5204 			rval = EFAULT;
5205 		}
5206 		break;
5207 	}
5208 #else /* ! _MULTI_DATAMODE */
5209 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5210 		rval = ERANGE;
5211 	} else {
5212 		passed.mt_op = local.mt_op;
5213 		passed.mt_count = local.mt_count;
5214 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5215 			rval = EFAULT;
5216 		}
5217 	}
5218 #endif /* _MULTI_DATAMODE */
5219 
5220 
5221 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5222 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5223 	    un->un_pos.blkno, un->un_pos.eof);
5224 
5225 	if (un->un_pos.pmode == invalid) {
5226 		un->un_density_known = 0;
5227 	}
5228 
5229 	ASSERT(mutex_owned(ST_MUTEX));
5230 	return (rval);
5231 }
5232 
5233 static int
5234 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5235 {
5236 	struct mtlop local;
5237 	int rval;
5238 
5239 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5240 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5241 		return (EFAULT);
5242 	}
5243 
5244 	rval = st_do_mtioctop(un, &local);
5245 
5246 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5247 		rval = EFAULT;
5248 	}
5249 	return (rval);
5250 }
5251 
5252 
5253 static int
5254 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5255 {
5256 	dev_t dev = un->un_dev;
5257 	int savefile;
5258 	int rval = 0;
5259 
5260 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5261 
5262 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5263 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5264 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5265 	    "fileno=%x, blkno=%x, eof=%x\n",
5266 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5267 
5268 	un->un_status = 0;
5269 
5270 	/*
5271 	 * if we are going to mess with a tape, we have to make sure we have
5272 	 * one and are not offline (i.e. no tape is initialized).  We let
5273 	 * commands pass here that don't actually touch the tape, except for
5274 	 * loading and initialization (rewinding).
5275 	 */
5276 	if (un->un_state == ST_STATE_OFFLINE) {
5277 		switch (mtop->mt_op) {
5278 		case MTLOAD:
5279 		case MTNOP:
5280 			/*
5281 			 * We don't want strategy calling st_tape_init here,
5282 			 * so, change state
5283 			 */
5284 			un->un_state = ST_STATE_INITIALIZING;
5285 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5286 			    "st_do_mtioctop : OFFLINE state = %d\n",
5287 			    un->un_state);
5288 			break;
5289 		default:
5290 			/*
5291 			 * reinitialize by normal means
5292 			 */
5293 			rval = st_tape_init(dev);
5294 			if (rval) {
5295 				un->un_state = ST_STATE_INITIALIZING;
5296 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5297 				    "st_do_mtioctop : OFFLINE init failure ");
5298 				un->un_state = ST_STATE_OFFLINE;
5299 				un->un_pos.pmode = invalid;
5300 				if (rval != EACCES) {
5301 					rval = EIO;
5302 				}
5303 				return (rval);
5304 			}
5305 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5306 			break;
5307 		}
5308 	}
5309 
5310 	/*
5311 	 * If the file position is invalid, allow only those
5312 	 * commands that properly position the tape and fail
5313 	 * the rest with EIO
5314 	 */
5315 	if (un->un_pos.pmode == invalid) {
5316 		switch (mtop->mt_op) {
5317 		case MTWEOF:
5318 		case MTRETEN:
5319 		case MTERASE:
5320 		case MTEOM:
5321 		case MTFSF:
5322 		case MTFSR:
5323 		case MTBSF:
5324 		case MTNBSF:
5325 		case MTBSR:
5326 		case MTSRSZ:
5327 		case MTGRSZ:
5328 		case MTSEEK:
5329 		case MTBSSF:
5330 		case MTFSSF:
5331 			return (EIO);
5332 			/* NOTREACHED */
5333 		case MTREW:
5334 		case MTLOAD:
5335 		case MTOFFL:
5336 		case MTNOP:
5337 		case MTTELL:
5338 		case MTLOCK:
5339 		case MTUNLOCK:
5340 			break;
5341 
5342 		default:
5343 			return (ENOTTY);
5344 			/* NOTREACHED */
5345 		}
5346 	}
5347 
5348 	switch (mtop->mt_op) {
5349 	case MTERASE:
5350 		/*
5351 		 * MTERASE rewinds the tape, erase it completely, and returns
5352 		 * to the beginning of the tape
5353 		 */
5354 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5355 			un->un_status = KEY_WRITE_PROTECT;
5356 			un->un_err_resid = mtop->mt_count;
5357 			COPY_POS(&un->un_err_pos, &un->un_pos);
5358 			return (EACCES);
5359 		}
5360 		if (un->un_dp->options & ST_REEL) {
5361 			un->un_fmneeded = 2;
5362 		} else {
5363 			un->un_fmneeded = 1;
5364 		}
5365 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5366 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
5367 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
5368 			un->un_pos.pmode = invalid;
5369 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5370 			    "st_do_mtioctop : EIO space or erase or "
5371 			    "check den)\n");
5372 			rval = EIO;
5373 		} else {
5374 			/* QIC and helical scan rewind after erase */
5375 			if (un->un_dp->options & ST_REEL) {
5376 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
5377 			}
5378 		}
5379 		break;
5380 
5381 	case MTWEOF:
5382 		/*
5383 		 * write an end-of-file record
5384 		 */
5385 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5386 			un->un_status = KEY_WRITE_PROTECT;
5387 			un->un_err_resid = mtop->mt_count;
5388 			COPY_POS(&un->un_err_pos, &un->un_pos);
5389 			return (EACCES);
5390 		}
5391 
5392 		/*
5393 		 * zero count means just flush buffers
5394 		 * negative count is not permitted
5395 		 */
5396 		if (mtop->mt_count < 0) {
5397 			return (EINVAL);
5398 		}
5399 
5400 		/* Not on worm */
5401 		if (un->un_read_only == RDWR) {
5402 			un->un_test_append = 1;
5403 		}
5404 
5405 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5406 			if (st_determine_density(dev, B_WRITE)) {
5407 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5408 				    "st_do_mtioctop : EIO : MTWEOF can't "
5409 				    "determine density");
5410 				return (EIO);
5411 			}
5412 		}
5413 
5414 		rval = st_write_fm(dev, (int)mtop->mt_count);
5415 		if ((rval != 0) && (rval != EACCES)) {
5416 			/*
5417 			 * Failure due to something other than illegal
5418 			 * request results in loss of state (st_intr).
5419 			 */
5420 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5421 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5422 			    "file mark");
5423 			rval = EIO;
5424 		}
5425 		break;
5426 
5427 	case MTRETEN:
5428 		/*
5429 		 * retension the tape
5430 		 */
5431 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5432 		    st_cmd(dev, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5433 			un->un_pos.pmode = invalid;
5434 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5435 			    "st_do_mtioctop : EIO : MTRETEN ");
5436 			rval = EIO;
5437 		}
5438 		break;
5439 
5440 	case MTREW:
5441 		/*
5442 		 * rewind  the tape
5443 		 */
5444 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5445 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5446 			    "st_do_mtioctop : EIO:MTREW check "
5447 			    "density/wfm failed");
5448 			return (EIO);
5449 		}
5450 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
5451 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5452 			    "st_do_mtioctop : EIO : MTREW ");
5453 			rval = EIO;
5454 		}
5455 		break;
5456 
5457 	case MTOFFL:
5458 		/*
5459 		 * rewinds, and, if appropriate, takes the device offline by
5460 		 * unloading the tape
5461 		 */
5462 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5463 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5464 			    "st_do_mtioctop :EIO:MTOFFL check "
5465 			    "density/wfm failed");
5466 			return (EIO);
5467 		}
5468 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
5469 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5470 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5471 			    "st_do_mtioctop : EIO : MTOFFL");
5472 			return (EIO);
5473 		}
5474 		un->un_pos.eof = ST_NO_EOF;
5475 		un->un_laststate = un->un_state;
5476 		un->un_state = ST_STATE_OFFLINE;
5477 		un->un_mediastate = MTIO_EJECTED;
5478 		break;
5479 
5480 	case MTLOAD:
5481 		/*
5482 		 * This is to load a tape into the drive
5483 		 * Note that if the tape is not loaded, the device will have
5484 		 * to be opened via O_NDELAY or O_NONBLOCK.
5485 		 */
5486 		/*
5487 		 * Let's try and clean things up, if we are not
5488 		 * initializing, and then send in the load command, no
5489 		 * matter what.
5490 		 *
5491 		 * load after a media change by the user.
5492 		 */
5493 
5494 		if (un->un_state > ST_STATE_INITIALIZING) {
5495 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5496 		}
5497 		rval = st_cmd(dev, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5498 		/* Load command to a drive that doesn't support load */
5499 		if ((rval == EIO) &&
5500 		    ((un->un_status == KEY_NOT_READY) &&
5501 			/* Medium not present */
5502 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5503 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5504 		    (un->un_dp->type == MT_ISSTK9840) &&
5505 			/* CSL not present */
5506 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5507 			rval = ENOTTY;
5508 			break;
5509 		} else if (rval != EACCES) {
5510 			rval = EIO;
5511 		}
5512 		if (rval) {
5513 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5514 			    "st_do_mtioctop : %s : MTLOAD\n",
5515 			    rval == EACCES ? "EACCES" : "EIO");
5516 			/*
5517 			 * If load tape fails, who knows what happened...
5518 			 */
5519 			un->un_pos.pmode = invalid;
5520 			break;
5521 		}
5522 
5523 		/*
5524 		 * reset all counters appropriately using rewind, as if LOAD
5525 		 * succeeds, we are at BOT
5526 		 */
5527 		un->un_state = ST_STATE_INITIALIZING;
5528 
5529 		rval = st_tape_init(dev);
5530 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5531 			rval = 0;
5532 			break;
5533 		}
5534 
5535 		if (rval != 0) {
5536 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5537 			    "st_do_mtioctop : EIO : MTLOAD calls "
5538 			    "st_tape_init\n");
5539 			rval = EIO;
5540 			un->un_state = ST_STATE_OFFLINE;
5541 		}
5542 
5543 		break;
5544 
5545 	case MTNOP:
5546 		un->un_status = 0;		/* Reset status */
5547 		un->un_err_resid = 0;
5548 		mtop->mt_count = MTUNIT(dev);
5549 		break;
5550 
5551 	case MTEOM:
5552 		/*
5553 		 * positions the tape at a location just after the last file
5554 		 * written on the tape. For cartridge and 8 mm, this after
5555 		 * the last file mark; for reel, this is inbetween the two
5556 		 * last 2 file marks
5557 		 */
5558 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5559 		    (un->un_lastop == ST_OP_WRITE) ||
5560 		    (un->un_lastop == ST_OP_WEOF)) {
5561 			/*
5562 			 * If the command wants to move to logical end
5563 			 * of media, and we're already there, we're done.
5564 			 * If we were at logical eot, we reset the state
5565 			 * to be *not* at logical eot.
5566 			 *
5567 			 * If we're at physical or logical eot, we prohibit
5568 			 * forward space operations (unconditionally).
5569 			 *
5570 			 * Also if the last operation was a write of any
5571 			 * kind the tape is at EOD.
5572 			 */
5573 			return (0);
5574 		}
5575 		/*
5576 		 * physical tape position may not be what we've been
5577 		 * telling the user; adjust the request accordingly
5578 		 */
5579 		if (IN_EOF(un->un_pos)) {
5580 			un->un_pos.fileno++;
5581 			un->un_pos.blkno = 0;
5582 		}
5583 
5584 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5585 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5586 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5587 			    " failed");
5588 			return (EIO);
5589 		}
5590 
5591 		/*
5592 		 * st_find_eod() returns the last fileno we knew about;
5593 		 */
5594 		savefile = st_find_eod(dev);
5595 
5596 		if ((un->un_status != KEY_BLANK_CHECK) &&
5597 		    (un->un_status != SUN_KEY_EOT)) {
5598 			un->un_pos.pmode = invalid;
5599 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5600 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5601 			rval = EIO;
5602 		} else {
5603 			/*
5604 			 * For 1/2" reel tapes assume logical EOT marked
5605 			 * by two file marks or we don't care that we may
5606 			 * be extending the last file on the tape.
5607 			 */
5608 			if (un->un_dp->options & ST_REEL) {
5609 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
5610 				    SYNC_CMD)) {
5611 					un->un_pos.pmode = invalid;
5612 					ST_DEBUG2(ST_DEVINFO, st_label,
5613 					    SCSI_DEBUG,
5614 					    "st_do_mtioctop : EIO : MTEOM space"
5615 					    " cmd failed");
5616 					rval = EIO;
5617 					break;
5618 				}
5619 				/*
5620 				 * Fix up the block number.
5621 				 */
5622 				un->un_pos.blkno = 0;
5623 				un->un_err_pos.blkno = 0;
5624 			}
5625 			un->un_err_resid = 0;
5626 			un->un_pos.fileno = savefile;
5627 			un->un_pos.eof = ST_EOT;
5628 		}
5629 		un->un_status = 0;
5630 		break;
5631 
5632 	case MTFSF:
5633 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5634 		break;
5635 
5636 	case MTFSR:
5637 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5638 		break;
5639 
5640 	case MTBSF:
5641 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5642 		break;
5643 
5644 	case MTNBSF:
5645 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5646 		break;
5647 
5648 	case MTBSR:
5649 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5650 		break;
5651 
5652 	case MTBSSF:
5653 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5654 		break;
5655 
5656 	case MTFSSF:
5657 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5658 		break;
5659 
5660 	case MTSRSZ:
5661 
5662 		/*
5663 		 * Set record-size to that sent by user
5664 		 * Check to see if there is reason that the requested
5665 		 * block size should not be set.
5666 		 */
5667 
5668 		/* If requesting variable block size is it ok? */
5669 		if ((mtop->mt_count == 0) &&
5670 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5671 			return (ENOTTY);
5672 		}
5673 
5674 		/*
5675 		 * If requested block size is not variable "0",
5676 		 * is it less then minimum.
5677 		 */
5678 		if ((mtop->mt_count != 0) &&
5679 		    (mtop->mt_count < un->un_minbsize)) {
5680 			return (EINVAL);
5681 		}
5682 
5683 		/* Is the requested block size more then maximum */
5684 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5685 		    (un->un_maxbsize != 0)) {
5686 			return (EINVAL);
5687 		}
5688 
5689 		/* Is requested block size a modulus the device likes */
5690 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5691 			return (EINVAL);
5692 		}
5693 
5694 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5695 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5696 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5697 			return (EIO);
5698 		}
5699 
5700 		return (0);
5701 
5702 	case MTGRSZ:
5703 		/*
5704 		 * Get record-size to the user
5705 		 */
5706 		mtop->mt_count = un->un_bsize;
5707 		rval = 0;
5708 		break;
5709 
5710 	case MTTELL:
5711 		rval = st_update_block_pos(un);
5712 		mtop->mt_count = un->un_pos.lgclblkno;
5713 		break;
5714 
5715 	case MTSEEK:
5716 		rval = st_logical_block_locate(un, (uint64_t)mtop->mt_count,
5717 		    un->un_pos.partition);
5718 		/*
5719 		 * This bit of magic make mt print the actual position if
5720 		 * the resulting position was not what was asked for.
5721 		 */
5722 		if (rval == ESPIPE) {
5723 			rval = EIO;
5724 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
5725 				mtop->mt_op = MTTELL;
5726 				mtop->mt_count = un->un_pos.lgclblkno;
5727 			}
5728 		}
5729 		break;
5730 
5731 	case MTLOCK:
5732 		if (st_cmd(dev, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
5733 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5734 			    "st_do_mtioctop : EIO : MTLOCK");
5735 			rval = EIO;
5736 		}
5737 		break;
5738 
5739 	case MTUNLOCK:
5740 		if (st_cmd(dev, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
5741 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5742 			    "st_do_mtioctop : EIO : MTUNLOCK");
5743 			rval = EIO;
5744 		}
5745 		break;
5746 
5747 	default:
5748 		rval = ENOTTY;
5749 	}
5750 
5751 	return (rval);
5752 }
5753 
5754 
5755 /*
5756  * Run a command for uscsi ioctl.
5757  */
5758 static int
5759 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd, int flag)
5760 {
5761 	struct uscsi_cmd	*uscmd;
5762 	struct buf	*bp;
5763 	enum uio_seg	uioseg;
5764 	int	offline_state = 0;
5765 	int	err = 0;
5766 
5767 	GET_SOFT_STATE(dev);
5768 
5769 	ST_FUNC(ST_DEVINFO, st_ioctl_cmd);
5770 
5771 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5772 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5773 
5774 	ASSERT(mutex_owned(ST_MUTEX));
5775 
5776 	/*
5777 	 * We really don't know what commands are coming in here and
5778 	 * we don't want to limit the commands coming in.
5779 	 *
5780 	 * If st_tape_init() gets called from st_strategy(), then we
5781 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5782 	 * which it never will, as we set it below.  To prevent
5783 	 * st_tape_init() from getting called, we have to set state to other
5784 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5785 	 * achieves this purpose already.
5786 	 *
5787 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5788 	 * so other entry points to the driver might have the chance to call
5789 	 * st_tape_init().
5790 	 */
5791 	if (un->un_state == ST_STATE_OFFLINE) {
5792 		un->un_laststate = ST_STATE_OFFLINE;
5793 		un->un_state = ST_STATE_INITIALIZING;
5794 		offline_state = 1;
5795 	}
5796 
5797 	mutex_exit(ST_MUTEX);
5798 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag,
5799 	    ROUTE, &uscmd);
5800 	mutex_enter(ST_MUTEX);
5801 	if (err != 0) {
5802 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5803 		    "st_ioctl_cmd: scsi_uscsi_alloc_and_copyin failed\n");
5804 		goto exit;
5805 	}
5806 
5807 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
5808 
5809 	/* check to see if this command requires the drive to be reserved */
5810 	if (uscmd->uscsi_cdb != NULL) {
5811 		err = st_check_cdb_for_need_to_reserve(un,
5812 		    &((char *)uscmd->uscsi_cdb)[0]);
5813 		if (err) {
5814 			goto exit_free;
5815 		}
5816 	}
5817 
5818 	/*
5819 	 * Get buffer resources...
5820 	 */
5821 	while (un->un_sbuf_busy)
5822 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5823 	un->un_sbuf_busy = 1;
5824 
5825 #ifdef STDEBUG
5826 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0xf) > 6) {
5827 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5828 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5829 		    "uscsi cdb", uscmd->uscsi_cdb);
5830 		if (uscmd->uscsi_buflen) {
5831 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5832 			    "uscsi %s of %ld bytes %s %s space\n",
5833 			    (rw == B_READ) ? rd_str : wr_str,
5834 			    uscmd->uscsi_buflen,
5835 			    (rw == B_READ) ? "to" : "from",
5836 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
5837 		}
5838 	}
5839 #endif /* ST_DEBUG */
5840 
5841 	/*
5842 	 * Although st_ioctl_cmd() never makes use of these
5843 	 * now, we are just being safe and consistent.
5844 	 */
5845 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
5846 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
5847 
5848 	un->un_srqbufp = uscmd->uscsi_rqbuf;
5849 	bp = un->un_sbufp;
5850 	bzero(bp, sizeof (buf_t));
5851 	if (uscmd->uscsi_cdb != NULL) {
5852 		bp->b_forw =
5853 		    (struct buf *)(uintptr_t)((char *)uscmd->uscsi_cdb)[0];
5854 		bp->b_back = (struct buf *)uscmd;
5855 	}
5856 
5857 	mutex_exit(ST_MUTEX);
5858 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd,
5859 	    st_strategy, bp, NULL);
5860 	mutex_enter(ST_MUTEX);
5861 
5862 	/*
5863 	 * If scsi reset successful, don't write any filemarks.
5864 	 */
5865 	if ((err == 0) && (uscmd->uscsi_flags &
5866 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
5867 		un->un_fmneeded = 0;
5868 	}
5869 
5870 exit_free:
5871 	/*
5872 	 * Free resources
5873 	 */
5874 	un->un_sbuf_busy = 0;
5875 	un->un_srqbufp = NULL;
5876 
5877 	/*
5878 	 * If was a space command need to update logical block position.
5879 	 * If the command failed such that positioning is invalid, Don't
5880 	 * update the position as the user must do this to validate the
5881 	 * position for data protection.
5882 	 */
5883 	if ((uscmd->uscsi_cdb != NULL) &&
5884 	    (uscmd->uscsi_cdb[0] == SCMD_SPACE) &&
5885 	    (un->un_pos.pmode != invalid)) {
5886 		uchar_t status = un->un_status;
5887 		(void) st_update_block_pos(un);
5888 		un->un_status = status;
5889 	}
5890 	cv_signal(&un->un_sbuf_cv);
5891 	mutex_exit(ST_MUTEX);
5892 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
5893 	mutex_enter(ST_MUTEX);
5894 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5895 	    "st_ioctl_cmd returns 0x%x\n", err);
5896 
5897 exit:
5898 	/* don't lose offline state */
5899 	if (offline_state) {
5900 		un->un_state = ST_STATE_OFFLINE;
5901 	}
5902 
5903 	ASSERT(mutex_owned(ST_MUTEX));
5904 	return (err);
5905 }
5906 
5907 static int
5908 st_write_fm(dev_t dev, int wfm)
5909 {
5910 	int i;
5911 	int rval;
5912 
5913 	GET_SOFT_STATE(dev);
5914 
5915 	ST_FUNC(ST_DEVINFO, st_write_fm);
5916 
5917 	ASSERT(mutex_owned(ST_MUTEX));
5918 
5919 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5920 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5921 
5922 	/*
5923 	 * write one filemark at the time after EOT
5924 	 */
5925 	if (un->un_pos.eof >= ST_EOT) {
5926 		for (i = 0; i < wfm; i++) {
5927 			rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
5928 			if (rval == EACCES) {
5929 				return (rval);
5930 			}
5931 			if (rval != 0) {
5932 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5933 				    "st_write_fm : EIO : write EOT file mark");
5934 				return (EIO);
5935 			}
5936 		}
5937 	} else {
5938 		rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
5939 		if (rval == EACCES) {
5940 			return (rval);
5941 		}
5942 		if (rval) {
5943 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5944 			    "st_write_fm : EIO : write file mark");
5945 			return (EIO);
5946 		}
5947 	}
5948 
5949 	ASSERT(mutex_owned(ST_MUTEX));
5950 	return (0);
5951 }
5952 
5953 #ifdef STDEBUG
5954 static void
5955 start_dump(struct scsi_tape *un, struct buf *bp)
5956 {
5957 	struct scsi_pkt *pkt = BP_PKT(bp);
5958 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5959 
5960 	ST_FUNC(ST_DEVINFO, start_dump);
5961 
5962 	if ((st_debug & 0xf) < 6)
5963 		return;
5964 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5965 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5966 	    (void *)bp->b_forw, bp->b_bcount,
5967 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5968 
5969 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5970 	    "st_start: cdb",  (caddr_t)cdbp);
5971 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5972 	    "st_start: fileno=%d, blk=%d\n",
5973 	    un->un_pos.fileno, un->un_pos.blkno);
5974 }
5975 #endif
5976 
5977 
5978 /*
5979  * Command start && done functions
5980  */
5981 
5982 /*
5983  * st_start()
5984  *
5985  * Called from:
5986  *  st_strategy() to start a command.
5987  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5988  *  st_attach() when resuming from power down state.
5989  *  st_start_restart() to retry transport when device was previously busy.
5990  *  st_done_and_mutex_exit() to start the next command when previous is done.
5991  *
5992  * On entry:
5993  *  scsi_pkt may or may not be allocated.
5994  *
5995  */
5996 static void
5997 st_start(struct scsi_tape *un)
5998 {
5999 	struct buf *bp;
6000 	int status;
6001 
6002 	ST_FUNC(ST_DEVINFO, st_start);
6003 	ASSERT(mutex_owned(ST_MUTEX));
6004 
6005 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6006 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6007 
6008 	if ((bp = un->un_quef) == NULL) {
6009 		return;
6010 	}
6011 
6012 	ASSERT((bp->b_flags & B_DONE) == 0);
6013 
6014 	/*
6015 	 * Don't send more than un_throttle commands to the HBA
6016 	 */
6017 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6018 		return;
6019 	}
6020 
6021 	/*
6022 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6023 	 * build the command.
6024 	 */
6025 	if (BP_PKT(bp) == NULL) {
6026 		ASSERT((bp->b_flags & B_DONE) == 0);
6027 		st_make_cmd(un, bp, st_runout);
6028 		ASSERT((bp->b_flags & B_DONE) == 0);
6029 		status = geterror(bp);
6030 
6031 		/*
6032 		 * Some HBA's don't call bioerror() to set an error.
6033 		 * And geterror() returns zero if B_ERROR is not set.
6034 		 * So if we get zero we must check b_error.
6035 		 */
6036 		if (status == 0 && bp->b_error != 0) {
6037 			status = bp->b_error;
6038 			bioerror(bp, status);
6039 		}
6040 
6041 		/*
6042 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6043 		 * In tape ENOMEM has special meaning so we'll change it.
6044 		 */
6045 		if (status == ENOMEM) {
6046 			status = 0;
6047 			bioerror(bp, status);
6048 		}
6049 
6050 		/*
6051 		 * Did it fail and is it retryable?
6052 		 * If so return and wait for the callback through st_runout.
6053 		 * Also looks like scsi_init_pkt() will setup a callback even
6054 		 * if it isn't retryable.
6055 		 */
6056 		if (BP_PKT(bp) == NULL) {
6057 			if (status == 0) {
6058 				/*
6059 				 * If first attempt save state.
6060 				 */
6061 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6062 					un->un_laststate = un->un_state;
6063 					un->un_state = ST_STATE_RESOURCE_WAIT;
6064 				}
6065 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6066 				    "temp no resources for pkt\n");
6067 			} else {
6068 				/*
6069 				 * Unlikely that it would be retryable then not.
6070 				 */
6071 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6072 					un->un_state = un->un_laststate;
6073 				}
6074 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6075 				    "perm no resources for pkt errno = 0x%x\n",
6076 				    status);
6077 			}
6078 			return;
6079 		}
6080 		/*
6081 		 * Worked this time set the state back.
6082 		 */
6083 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6084 			un->un_state = un->un_laststate;
6085 		}
6086 	}
6087 
6088 	/*
6089 	 * move from waitq to runq
6090 	 */
6091 	un->un_quef = bp->b_actf;
6092 	if (un->un_quel == bp) {
6093 		/*
6094 		 *  For the case of queue having one
6095 		 *  element, set the tail pointer to
6096 		 *  point to the element.
6097 		 */
6098 		un->un_quel = bp->b_actf;
6099 	}
6100 
6101 	bp->b_actf = NULL;
6102 
6103 	if (un->un_runqf) {
6104 		un->un_runql->b_actf = bp;
6105 	} else {
6106 		un->un_runqf = bp;
6107 	}
6108 	un->un_runql = bp;
6109 
6110 
6111 	ST_CDB(ST_DEVINFO, "Start CDB", (char *)BP_PKT(bp)->pkt_cdbp);
6112 
6113 #ifdef STDEBUG
6114 	start_dump(un, bp);
6115 #endif
6116 
6117 	/* could not get here if throttle was zero */
6118 	un->un_last_throttle = un->un_throttle;
6119 	un->un_throttle = 0;	/* so nothing else will come in here */
6120 	un->un_ncmds++;
6121 
6122 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6123 
6124 	mutex_exit(ST_MUTEX);
6125 
6126 	status = scsi_transport(BP_PKT(bp));
6127 
6128 	mutex_enter(ST_MUTEX);
6129 
6130 	if (un->un_last_throttle) {
6131 		un->un_throttle = un->un_last_throttle;
6132 	}
6133 
6134 	if (status != TRAN_ACCEPT) {
6135 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6136 		mutex_exit(ST_MUTEX);
6137 
6138 		if (status == TRAN_BUSY) {
6139 			/* if too many retries, fail the transport */
6140 			if (st_handle_start_busy(un, bp,
6141 			    ST_TRAN_BUSY_TIMEOUT) == 0)
6142 				goto done;
6143 		}
6144 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6145 		    "transport rejected\n");
6146 		bp->b_resid = bp->b_bcount;
6147 
6148 
6149 #ifndef __lock_lint
6150 		/*
6151 		 * warlock doesn't understand this potential
6152 		 * recursion?
6153 		 */
6154 		mutex_enter(ST_MUTEX);
6155 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6156 		ST_DO_ERRSTATS(un, st_transerrs);
6157 		st_bioerror(bp, EIO);
6158 		SET_PE_FLAG(un);
6159 		st_done_and_mutex_exit(un, bp);
6160 #endif
6161 	} else {
6162 		un->un_tran_retry_ct = 0;
6163 		mutex_exit(ST_MUTEX);
6164 	}
6165 
6166 done:
6167 
6168 	mutex_enter(ST_MUTEX);
6169 }
6170 
6171 /*
6172  * if the transport is busy, then put this bp back on the waitq
6173  */
6174 static int
6175 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6176     clock_t timeout_interval)
6177 {
6178 	struct buf *last_quef, *runq_bp;
6179 	int rval = 0;
6180 
6181 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6182 
6183 	mutex_enter(ST_MUTEX);
6184 
6185 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6186 	    "st_handle_start_busy()\n");
6187 
6188 	/*
6189 	 * Check to see if we hit the retry timeout and one last check for
6190 	 * making sure this is the last on the runq, if it is not, we have
6191 	 * to fail
6192 	 */
6193 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6194 	    (un->un_runql != bp)) {
6195 		rval = -1;
6196 		goto exit;
6197 	}
6198 
6199 	/* put the bp back on the waitq */
6200 	if (un->un_quef) {
6201 		last_quef = un->un_quef;
6202 		un->un_quef = bp;
6203 		bp->b_actf = last_quef;
6204 	} else  {
6205 		bp->b_actf = NULL;
6206 		un->un_quef = bp;
6207 		un->un_quel = bp;
6208 	}
6209 
6210 	/*
6211 	 * Decrement un_ncmds so that this
6212 	 * gets thru' st_start() again.
6213 	 */
6214 	un->un_ncmds--;
6215 
6216 	/*
6217 	 * since this is an error case, we won't have to do
6218 	 * this list walking much.  We've already made sure this bp was the
6219 	 * last on the runq
6220 	 */
6221 	runq_bp = un->un_runqf;
6222 
6223 	if (un->un_runqf == bp) {
6224 		un->un_runqf = NULL;
6225 		un->un_runql = NULL;
6226 	} else {
6227 		while (runq_bp) {
6228 			if (runq_bp->b_actf == bp) {
6229 				runq_bp->b_actf = NULL;
6230 				un->un_runql = runq_bp;
6231 				break;
6232 			}
6233 			runq_bp = runq_bp->b_actf;
6234 		}
6235 	}
6236 
6237 
6238 	/*
6239 	 * send a marker pkt, if appropriate
6240 	 */
6241 	st_hba_unflush(un);
6242 
6243 	/*
6244 	 * all queues are aligned, we are just waiting to
6245 	 * transport, don't alloc any more buf p's, when
6246 	 * st_start is reentered.
6247 	 */
6248 	(void) timeout(st_start_restart, un, timeout_interval);
6249 
6250 exit:
6251 	mutex_exit(ST_MUTEX);
6252 	return (rval);
6253 }
6254 
6255 
6256 /*
6257  * st_runout a callback that is called what a resource allocatation failed
6258  */
6259 static int
6260 st_runout(caddr_t arg)
6261 {
6262 	struct scsi_tape *un = (struct scsi_tape *)arg;
6263 	struct buf *bp;
6264 	ASSERT(un != NULL);
6265 
6266 	ST_FUNC(ST_DEVINFO, st_runout);
6267 
6268 	mutex_enter(ST_MUTEX);
6269 
6270 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6271 
6272 	bp = un->un_quef;
6273 
6274 	/*
6275 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6276 	 */
6277 	if ((bp != NULL) && (geterror(bp) != 0)) {
6278 
6279 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6280 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6281 		    bp->b_flags, geterror(bp));
6282 		ASSERT((bp->b_flags & B_DONE) == 0);
6283 
6284 		un->un_quef = bp->b_actf;
6285 		if (un->un_quel == bp) {
6286 			/*
6287 			 *  For the case of queue having one
6288 			 *  element, set the tail pointer to
6289 			 *  point to the element.
6290 			 */
6291 			un->un_quel = bp->b_actf;
6292 		}
6293 		mutex_exit(ST_MUTEX);
6294 		bp->b_actf = NULL;
6295 
6296 		ASSERT((bp->b_flags & B_DONE) == 0);
6297 
6298 		/*
6299 		 * Set resid, Error already set, then unblock calling thread.
6300 		 */
6301 		bp->b_resid = bp->b_bcount;
6302 		biodone(bp);
6303 	} else {
6304 		/*
6305 		 * Try Again
6306 		 */
6307 		st_start(un);
6308 		mutex_exit(ST_MUTEX);
6309 	}
6310 
6311 	/*
6312 	 * Comments courtesy of sd.c
6313 	 * The scsi_init_pkt routine allows for the callback function to
6314 	 * return a 0 indicating the callback should be rescheduled or a 1
6315 	 * indicating not to reschedule. This routine always returns 1
6316 	 * because the driver always provides a callback function to
6317 	 * scsi_init_pkt. This results in a callback always being scheduled
6318 	 * (via the scsi_init_pkt callback implementation) if a resource
6319 	 * failure occurs.
6320 	 */
6321 
6322 	return (1);
6323 }
6324 
6325 /*
6326  * st_done_and_mutex_exit()
6327  *	- remove bp from runq
6328  *	- start up the next request
6329  *	- if this was an asynch bp, clean up
6330  *	- exit with released mutex
6331  */
6332 static void
6333 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6334 {
6335 	struct buf *runqbp, *prevbp;
6336 	int	pe_flagged = 0;
6337 
6338 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6339 #if !defined(lint)
6340 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6341 #endif
6342 
6343 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6344 
6345 	ASSERT(mutex_owned(ST_MUTEX));
6346 
6347 	/*
6348 	 * if bp is still on the runq (anywhere), then remove it
6349 	 */
6350 	prevbp = NULL;
6351 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
6352 		if (runqbp == bp) {
6353 			if (runqbp == un->un_runqf) {
6354 				un->un_runqf = bp->b_actf;
6355 			} else {
6356 				prevbp->b_actf = bp->b_actf;
6357 			}
6358 			if (un->un_runql == bp) {
6359 				un->un_runql = prevbp;
6360 			}
6361 			break;
6362 		}
6363 		prevbp = runqbp;
6364 	}
6365 	bp->b_actf = NULL;
6366 
6367 	un->un_ncmds--;
6368 	cv_signal(&un->un_queue_cv);
6369 
6370 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6371 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6372 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
6373 	    bp->b_resid, bp->b_flags);
6374 
6375 
6376 	/*
6377 	 * update kstats with transfer count info
6378 	 */
6379 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6380 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6381 		if (bp->b_flags & B_READ) {
6382 			IOSP->reads++;
6383 			IOSP->nread += n_done;
6384 		} else {
6385 			IOSP->writes++;
6386 			IOSP->nwritten += n_done;
6387 		}
6388 	}
6389 
6390 	/*
6391 	 * Start the next one before releasing resources on this one, if
6392 	 * there is something on the queue and persistent errors has not been
6393 	 * flagged
6394 	 */
6395 
6396 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
6397 		un->un_last_resid = bp->b_resid;
6398 		un->un_last_count = bp->b_bcount;
6399 	}
6400 
6401 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6402 		cv_broadcast(&un->un_tape_busy_cv);
6403 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
6404 		st_start(un);
6405 	}
6406 
6407 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6408 		/*
6409 		 * Since we marked this ourselves as ASYNC,
6410 		 * there isn't anybody around waiting for
6411 		 * completion any more.
6412 		 */
6413 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
6414 		if (com == SCMD_READ || com == SCMD_WRITE) {
6415 			bp->b_un.b_addr = (caddr_t)0;
6416 		}
6417 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6418 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6419 		scsi_destroy_pkt(BP_PKT(bp));
6420 		un->un_sbuf_busy = 0;
6421 		cv_signal(&un->un_sbuf_cv);
6422 		mutex_exit(ST_MUTEX);
6423 		return;
6424 	}
6425 
6426 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6427 		/*
6428 		 * Copy status from scsi_pkt to uscsi_cmd
6429 		 * since st_ioctl_cmd needs it
6430 		 */
6431 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6432 	}
6433 
6434 
6435 #ifdef STDEBUG
6436 	if (((st_debug & 0xf) >= 4) &&
6437 	    (((un->un_pos.blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
6438 
6439 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6440 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6441 		    "un_errno = %d, un_pe = %d\n",
6442 		    un->un_ncmds, un->un_throttle, un->un_errno,
6443 		    un->un_persist_errors);
6444 	}
6445 
6446 #endif
6447 
6448 	mutex_exit(ST_MUTEX);
6449 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6450 	    "st_done_and_mutex_exit: freeing pkt\n");
6451 
6452 	scsi_destroy_pkt(BP_PKT(bp));
6453 
6454 	biodone(bp);
6455 
6456 	/*
6457 	 * now that we biodoned that command, if persistent errors have been
6458 	 * flagged, flush the waitq
6459 	 */
6460 	if (pe_flagged)
6461 		st_flush(un);
6462 }
6463 
6464 
6465 /*
6466  * Tape error, flush tape driver queue.
6467  */
6468 static void
6469 st_flush(struct scsi_tape *un)
6470 {
6471 	struct buf *bp;
6472 
6473 	ST_FUNC(ST_DEVINFO, st_flush);
6474 
6475 	mutex_enter(ST_MUTEX);
6476 
6477 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6478 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6479 	    un->un_ncmds, (void *)un->un_quef);
6480 
6481 	/*
6482 	 * if we still have commands outstanding, wait for them to come in
6483 	 * before flushing the queue, and make sure there is a queue
6484 	 */
6485 	if (un->un_ncmds || !un->un_quef)
6486 		goto exit;
6487 
6488 	/*
6489 	 * we have no more commands outstanding, so let's deal with special
6490 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6491 	 * is 0, then we know there was no error and we return a 0 read or
6492 	 * write before showing errors
6493 	 */
6494 
6495 	/* Flush the wait queue. */
6496 	while ((bp = un->un_quef) != NULL) {
6497 		un->un_quef = bp->b_actf;
6498 
6499 		bp->b_resid = bp->b_bcount;
6500 
6501 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6502 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6503 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6504 
6505 		st_set_pe_errno(un);
6506 
6507 		bioerror(bp, un->un_errno);
6508 
6509 		mutex_exit(ST_MUTEX);
6510 		/* it should have one, but check anyway */
6511 		if (BP_PKT(bp)) {
6512 			scsi_destroy_pkt(BP_PKT(bp));
6513 		}
6514 		biodone(bp);
6515 		mutex_enter(ST_MUTEX);
6516 	}
6517 
6518 	/*
6519 	 * It's not a bad practice to reset the
6520 	 * waitq tail pointer to NULL.
6521 	 */
6522 	un->un_quel = NULL;
6523 
6524 exit:
6525 	/* we mucked with the queue, so let others know about it */
6526 	cv_signal(&un->un_queue_cv);
6527 	mutex_exit(ST_MUTEX);
6528 }
6529 
6530 
6531 /*
6532  * Utility functions
6533  */
6534 static int
6535 st_determine_generic(dev_t dev)
6536 {
6537 	int bsize;
6538 	static char *cart = "0.25 inch cartridge";
6539 	char *sizestr;
6540 
6541 	GET_SOFT_STATE(dev);
6542 
6543 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6544 
6545 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6546 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6547 
6548 	ASSERT(mutex_owned(ST_MUTEX));
6549 
6550 	if (st_modesense(un)) {
6551 		return (-1);
6552 	}
6553 
6554 	bsize = (un->un_mspl->high_bl << 16)	|
6555 	    (un->un_mspl->mid_bl << 8)	|
6556 	    (un->un_mspl->low_bl);
6557 
6558 	if (bsize == 0) {
6559 		un->un_dp->options |= ST_VARIABLE;
6560 		un->un_dp->bsize = 0;
6561 		un->un_bsize = 0;
6562 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6563 		/*
6564 		 * record size of this device too big.
6565 		 * try and convert it to variable record length.
6566 		 *
6567 		 */
6568 		un->un_dp->options |= ST_VARIABLE;
6569 		if (st_change_block_size(dev, 0) != 0) {
6570 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6571 			    "Fixed Record Size %d is too large\n", bsize);
6572 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6573 			    "Cannot switch to variable record size\n");
6574 			un->un_dp->options &= ~ST_VARIABLE;
6575 			return (-1);
6576 		}
6577 	} else if (st_change_block_size(dev, 0) == 0) {
6578 		/*
6579 		 * If the drive was set to a non zero block size,
6580 		 * See if it can be set to a zero block size.
6581 		 * If it works, ST_VARIABLE so user can set it as they want.
6582 		 */
6583 		un->un_dp->options |= ST_VARIABLE;
6584 		un->un_dp->bsize = 0;
6585 		un->un_bsize = 0;
6586 	} else {
6587 		un->un_dp->bsize = bsize;
6588 		un->un_bsize = bsize;
6589 	}
6590 
6591 
6592 	switch (un->un_mspl->density) {
6593 	default:
6594 	case 0x0:
6595 		/*
6596 		 * default density, cannot determine any other
6597 		 * information.
6598 		 */
6599 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6600 		un->un_dp->type = ST_TYPE_DEFAULT;
6601 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6602 		break;
6603 	case 0x1:
6604 	case 0x2:
6605 	case 0x3:
6606 	case 0x6:
6607 		/*
6608 		 * 1/2" reel
6609 		 */
6610 		sizestr = "0.50 inch reel";
6611 		un->un_dp->type = ST_TYPE_REEL;
6612 		un->un_dp->options |= ST_REEL;
6613 		un->un_dp->densities[0] = 0x1;
6614 		un->un_dp->densities[1] = 0x2;
6615 		un->un_dp->densities[2] = 0x6;
6616 		un->un_dp->densities[3] = 0x3;
6617 		break;
6618 	case 0x4:
6619 	case 0x5:
6620 	case 0x7:
6621 	case 0x0b:
6622 
6623 		/*
6624 		 * Quarter inch.
6625 		 */
6626 		sizestr = cart;
6627 		un->un_dp->type = ST_TYPE_DEFAULT;
6628 		un->un_dp->options |= ST_QIC;
6629 
6630 		un->un_dp->densities[1] = 0x4;
6631 		un->un_dp->densities[2] = 0x5;
6632 		un->un_dp->densities[3] = 0x7;
6633 		un->un_dp->densities[0] = 0x0b;
6634 		break;
6635 
6636 	case 0x0f:
6637 	case 0x10:
6638 	case 0x11:
6639 	case 0x12:
6640 		/*
6641 		 * QIC-120, QIC-150, QIC-320, QIC-600
6642 		 */
6643 		sizestr = cart;
6644 		un->un_dp->type = ST_TYPE_DEFAULT;
6645 		un->un_dp->options |= ST_QIC;
6646 		un->un_dp->densities[0] = 0x0f;
6647 		un->un_dp->densities[1] = 0x10;
6648 		un->un_dp->densities[2] = 0x11;
6649 		un->un_dp->densities[3] = 0x12;
6650 		break;
6651 
6652 	case 0x09:
6653 	case 0x0a:
6654 	case 0x0c:
6655 	case 0x0d:
6656 		/*
6657 		 * 1/2" cartridge tapes. Include HI-TC.
6658 		 */
6659 		sizestr = cart;
6660 		sizestr[2] = '5';
6661 		sizestr[3] = '0';
6662 		un->un_dp->type = ST_TYPE_HIC;
6663 		un->un_dp->densities[0] = 0x09;
6664 		un->un_dp->densities[1] = 0x0a;
6665 		un->un_dp->densities[2] = 0x0c;
6666 		un->un_dp->densities[3] = 0x0d;
6667 		break;
6668 
6669 	case 0x13:
6670 			/* DDS-2/DDS-3 scsi spec densities */
6671 	case 0x24:
6672 	case 0x25:
6673 	case 0x26:
6674 		sizestr = "DAT Data Storage (DDS)";
6675 		un->un_dp->type = ST_TYPE_DAT;
6676 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6677 		break;
6678 
6679 	case 0x14:
6680 		/*
6681 		 * Helical Scan (Exabyte) devices
6682 		 */
6683 		sizestr = "8mm helical scan cartridge";
6684 		un->un_dp->type = ST_TYPE_EXABYTE;
6685 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6686 		break;
6687 	}
6688 
6689 	/*
6690 	 * Assume LONG ERASE, BSF and BSR
6691 	 */
6692 
6693 	un->un_dp->options |=
6694 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6695 
6696 	/*
6697 	 * Only if mode sense data says no buffered write, set NOBUF
6698 	 */
6699 	if (un->un_mspl->bufm == 0)
6700 		un->un_dp->options |= ST_NOBUF;
6701 
6702 	/*
6703 	 * set up large read and write retry counts
6704 	 */
6705 
6706 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6707 
6708 	/*
6709 	 * If this is a 0.50 inch reel tape, and
6710 	 * it is *not* variable mode, try and
6711 	 * set it to variable record length
6712 	 * mode.
6713 	 */
6714 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6715 	    (un->un_dp->options & ST_VARIABLE)) {
6716 		if (st_change_block_size(dev, 0) == 0) {
6717 			un->un_dp->bsize = 0;
6718 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6719 			    un->un_mspl->low_bl = 0;
6720 		}
6721 	}
6722 
6723 	/*
6724 	 * Write to console about type of device found
6725 	 */
6726 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6727 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6728 	    sizestr);
6729 	if (un->un_dp->options & ST_VARIABLE) {
6730 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6731 		    "!Variable record length I/O\n");
6732 	} else {
6733 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6734 		    "!Fixed record length (%d byte blocks) I/O\n",
6735 		    un->un_dp->bsize);
6736 	}
6737 	ASSERT(mutex_owned(ST_MUTEX));
6738 	return (0);
6739 }
6740 
6741 static int
6742 st_determine_density(dev_t dev, int rw)
6743 {
6744 	int rval = 0;
6745 
6746 	GET_SOFT_STATE(dev);
6747 
6748 	ST_FUNC(ST_DEVINFO, st_determine_density);
6749 
6750 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6751 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6752 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6753 
6754 	ASSERT(mutex_owned(ST_MUTEX));
6755 
6756 	/*
6757 	 * If we're past BOT, density is determined already.
6758 	 */
6759 	if (un->un_pos.pmode == logical) {
6760 		if (un->un_pos.lgclblkno != 0) {
6761 			goto exit;
6762 		}
6763 	} else if (un->un_pos.pmode == legacy) {
6764 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
6765 			/*
6766 			 * XXX: put in a bitch message about attempting to
6767 			 * XXX: change density past BOT.
6768 			 */
6769 			goto exit;
6770 		}
6771 	} else {
6772 		goto exit;
6773 	}
6774 
6775 
6776 	/*
6777 	 * If we're going to be writing, we set the density
6778 	 */
6779 	if (rw == 0 || rw == B_WRITE) {
6780 		/* un_curdens is used as an index into densities table */
6781 		un->un_curdens = MT_DENSITY(un->un_dev);
6782 		if (st_set_density(dev)) {
6783 			rval = -1;
6784 		}
6785 		goto exit;
6786 	}
6787 
6788 	/*
6789 	 * If density is known already,
6790 	 * we don't have to get it again.(?)
6791 	 */
6792 	if (!un->un_density_known) {
6793 		if (st_get_density(dev)) {
6794 			rval = -1;
6795 		}
6796 	}
6797 
6798 exit:
6799 	ASSERT(mutex_owned(ST_MUTEX));
6800 	return (rval);
6801 }
6802 
6803 
6804 /*
6805  * Try to determine density. We do this by attempting to read the
6806  * first record off the tape, cycling through the available density
6807  * codes as we go.
6808  */
6809 
6810 static int
6811 st_get_density(dev_t dev)
6812 {
6813 	int succes = 0, rval = -1, i;
6814 	uint_t size;
6815 	uchar_t dens, olddens;
6816 
6817 	GET_SOFT_STATE(dev);
6818 
6819 	ST_FUNC(ST_DEVINFO, st_get_density);
6820 
6821 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6822 	    "st_get_density(dev = 0x%lx)\n", dev);
6823 
6824 	ASSERT(mutex_owned(ST_MUTEX));
6825 
6826 	/*
6827 	 * If Auto Density override is enabled The drive has
6828 	 * only one density and there is no point in attempting
6829 	 * find the correct one.
6830 	 *
6831 	 * Since most modern drives auto detect the density
6832 	 * and format of the recorded media before they come
6833 	 * ready. What this function does is a legacy behavior
6834 	 * and modern drives not only don't need it, The backup
6835 	 * utilities that do positioning via uscsi find the un-
6836 	 * expected rewinds problematic.
6837 	 *
6838 	 * The drives that need this are old reel to reel devices.
6839 	 * I took a swag and said they must be scsi-1 or older.
6840 	 * I don't beleave there will any of the newer devices
6841 	 * that need this. There will be some scsi-1 devices that
6842 	 * don't need this but I don't think they will be using the
6843 	 * BIG aftermarket backup and restore utilitys.
6844 	 */
6845 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6846 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6847 		un->un_density_known = 1;
6848 		rval = 0;
6849 		goto exit;
6850 	}
6851 
6852 	/*
6853 	 * This will only work on variable record length tapes
6854 	 * if and only if all variable record length tapes autodensity
6855 	 * select.
6856 	 */
6857 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6858 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6859 
6860 	/*
6861 	 * Start at the specified density
6862 	 */
6863 
6864 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6865 
6866 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6867 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
6868 		/*
6869 		 * If we've done this density before,
6870 		 * don't bother to do it again.
6871 		 */
6872 		dens = un->un_dp->densities[un->un_curdens];
6873 		if (i > 0 && dens == olddens)
6874 			continue;
6875 		olddens = dens;
6876 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6877 		    "trying density 0x%x\n", dens);
6878 		if (st_set_density(dev)) {
6879 			continue;
6880 		}
6881 
6882 		/*
6883 		 * XXX - the creates lots of headaches and slowdowns - must
6884 		 * fix.
6885 		 */
6886 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6887 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6888 			break;
6889 		}
6890 		if (succes) {
6891 			st_init(un);
6892 			rval = 0;
6893 			un->un_density_known = 1;
6894 			break;
6895 		}
6896 	}
6897 	kmem_free(un->un_tmpbuf, size);
6898 	un->un_tmpbuf = 0;
6899 
6900 exit:
6901 	ASSERT(mutex_owned(ST_MUTEX));
6902 	return (rval);
6903 }
6904 
6905 static int
6906 st_set_density(dev_t dev)
6907 {
6908 	int rval = 0;
6909 
6910 	GET_SOFT_STATE(dev);
6911 
6912 	ST_FUNC(ST_DEVINFO, st_set_density);
6913 
6914 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6915 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6916 	    un->un_dp->densities[un->un_curdens]);
6917 
6918 	ASSERT(mutex_owned(ST_MUTEX));
6919 
6920 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6921 
6922 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6923 		/*
6924 		 * If auto density override is not set, Use mode select
6925 		 * to set density and compression.
6926 		 */
6927 		if (st_modeselect(un)) {
6928 			rval = -1;
6929 		}
6930 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6931 		/*
6932 		 * If auto density and mode select compression are set,
6933 		 * This is a drive with one density code but compression
6934 		 * can be enabled or disabled.
6935 		 * Set compression but no need to set density.
6936 		 */
6937 		rval = st_set_compression(un);
6938 		if ((rval != 0) && (rval != EALREADY)) {
6939 			rval = -1;
6940 		} else {
6941 			rval = 0;
6942 		}
6943 	}
6944 
6945 	/* If sucessful set density and/or compression, mark density known */
6946 	if (rval == 0) {
6947 		un->un_density_known = 1;
6948 	}
6949 
6950 	ASSERT(mutex_owned(ST_MUTEX));
6951 	return (rval);
6952 }
6953 
6954 static int
6955 st_loadtape(dev_t dev)
6956 {
6957 	int rval;
6958 
6959 	GET_SOFT_STATE(dev);
6960 
6961 	ST_FUNC(ST_DEVINFO, st_load_tape);
6962 
6963 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6964 	    "st_loadtape(dev = 0x%lx)\n", dev);
6965 
6966 	ASSERT(mutex_owned(ST_MUTEX));
6967 
6968 	/*
6969 	 * 'LOAD' the tape to BOT by rewinding
6970 	 */
6971 	rval = st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD);
6972 	if (rval == 0) {
6973 		st_init(un);
6974 		un->un_density_known = 0;
6975 	}
6976 
6977 	ASSERT(mutex_owned(ST_MUTEX));
6978 	return (rval);
6979 }
6980 
6981 
6982 /*
6983  * Note: QIC devices aren't so smart.  If you try to append
6984  * after EOM, the write can fail because the device doesn't know
6985  * it's at EOM.	 In that case, issue a read.  The read should fail
6986  * because there's no data, but the device knows it's at EOM,
6987  * so a subsequent write should succeed.  To further confuse matters,
6988  * the target returns the same error if the tape is positioned
6989  * such that a write would overwrite existing data.  That's why
6990  * we have to do the append test.  A read in the middle of
6991  * recorded data would succeed, thus indicating we're attempting
6992  * something illegal.
6993  */
6994 
6995 
6996 static void
6997 st_test_append(struct buf *bp)
6998 {
6999 	dev_t dev = bp->b_edev;
7000 	struct scsi_tape *un;
7001 	uchar_t status;
7002 	unsigned bcount;
7003 
7004 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7005 
7006 	ST_FUNC(ST_DEVINFO, st_test_append);
7007 
7008 	ASSERT(mutex_owned(ST_MUTEX));
7009 
7010 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7011 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7012 
7013 	un->un_laststate = un->un_state;
7014 	un->un_state = ST_STATE_APPEND_TESTING;
7015 	un->un_test_append = 0;
7016 
7017 	/*
7018 	 * first, map in the buffer, because we're doing a double write --
7019 	 * first into the kernel, then onto the tape.
7020 	 */
7021 	bp_mapin(bp);
7022 
7023 	/*
7024 	 * get a copy of the data....
7025 	 */
7026 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7027 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7028 
7029 	/*
7030 	 * attempt the write..
7031 	 */
7032 
7033 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7034 success:
7035 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7036 		    "append write succeeded\n");
7037 		bp->b_resid = un->un_sbufp->b_resid;
7038 		mutex_exit(ST_MUTEX);
7039 		bcount = (unsigned)bp->b_bcount;
7040 		biodone(bp);
7041 		mutex_enter(ST_MUTEX);
7042 		un->un_laststate = un->un_state;
7043 		un->un_state = ST_STATE_OPEN;
7044 		kmem_free(un->un_tmpbuf, bcount);
7045 		un->un_tmpbuf = NULL;
7046 		return;
7047 	}
7048 
7049 	/*
7050 	 * The append failed. Do a short read. If that fails,  we are at EOM
7051 	 * so we can retry the write command. If that succeeds, than we're
7052 	 * all screwed up (the controller reported a real error).
7053 	 *
7054 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7055 	 * XXX: block size?
7056 	 *
7057 	 */
7058 	status = un->un_status;
7059 	un->un_status = 0;
7060 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
7061 	if (un->un_status == KEY_BLANK_CHECK) {
7062 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7063 		    "append at EOM\n");
7064 		/*
7065 		 * Okay- the read failed. We should actually have confused
7066 		 * the controller enough to allow writing. In any case, the
7067 		 * i/o is on its own from here on out.
7068 		 */
7069 		un->un_laststate = un->un_state;
7070 		un->un_state = ST_STATE_OPEN;
7071 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7072 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
7073 		    SYNC_CMD) == 0) {
7074 			goto success;
7075 		}
7076 	}
7077 
7078 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7079 	    "append write failed- not at EOM\n");
7080 	bp->b_resid = bp->b_bcount;
7081 	st_bioerror(bp, EIO);
7082 
7083 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7084 	    "st_test_append : EIO : append write failed - not at EOM");
7085 
7086 	/*
7087 	 * backspace one record to get back to where we were
7088 	 */
7089 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7090 		un->un_pos.pmode = invalid;
7091 	}
7092 
7093 	un->un_err_resid = bp->b_resid;
7094 	un->un_status = status;
7095 
7096 	/*
7097 	 * Note: biodone will do a bp_mapout()
7098 	 */
7099 	mutex_exit(ST_MUTEX);
7100 	bcount = (unsigned)bp->b_bcount;
7101 	biodone(bp);
7102 	mutex_enter(ST_MUTEX);
7103 	un->un_laststate = un->un_state;
7104 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7105 	kmem_free(un->un_tmpbuf, bcount);
7106 	un->un_tmpbuf = NULL;
7107 }
7108 
7109 /*
7110  * Special command handler
7111  */
7112 
7113 /*
7114  * common st_cmd code. The fourth parameter states
7115  * whether the caller wishes to await the results
7116  * Note the release of the mutex during most of the function
7117  */
7118 static int
7119 st_cmd(dev_t dev, int com, int count, int wait)
7120 {
7121 	struct buf *bp;
7122 	int err;
7123 
7124 	GET_SOFT_STATE(dev);
7125 
7126 	ST_FUNC(ST_DEVINFO, st_cmd);
7127 
7128 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7129 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
7130 	    dev, com, count, wait);
7131 
7132 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7133 	ASSERT(mutex_owned(ST_MUTEX));
7134 
7135 #ifdef STDEBUG
7136 	if ((st_debug & 0xf)) {
7137 		st_debug_cmds(un, com, count, wait);
7138 	}
7139 #endif
7140 
7141 	/* check to see if this command requires the drive to be reserved */
7142 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7143 
7144 	if (err) {
7145 		return (err);
7146 	}
7147 
7148 	while (un->un_sbuf_busy)
7149 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7150 	un->un_sbuf_busy = 1;
7151 
7152 	bp = un->un_sbufp;
7153 	bzero(bp, sizeof (buf_t));
7154 
7155 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7156 
7157 	/*
7158 	 * Set count to the actual size of the data tranfer.
7159 	 * For commands with no data transfer, set bp->b_bcount
7160 	 * to the value to be used when constructing the
7161 	 * cdb in st_make_cmd().
7162 	 */
7163 	switch (com) {
7164 	case SCMD_READ:
7165 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7166 		    "special read %d\n", count);
7167 		bp->b_flags |= B_READ;
7168 		bp->b_un.b_addr = un->un_tmpbuf;
7169 		break;
7170 
7171 	case SCMD_WRITE:
7172 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7173 		    "special write %d\n", count);
7174 		bp->b_un.b_addr = un->un_tmpbuf;
7175 		break;
7176 
7177 	case SCMD_WRITE_FILE_MARK:
7178 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7179 		    "write %d file marks\n", count);
7180 		bp->b_bcount = count;
7181 		count = 0;
7182 		break;
7183 
7184 	case SCMD_REWIND:
7185 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7186 		bp->b_bcount = 0;
7187 		count = 0;
7188 		break;
7189 
7190 	case SCMD_SPACE:
7191 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7192 		/*
7193 		 * XXX The user could have entered a number that will
7194 		 * not fit in the 12 bit count field. Whats new here
7195 		 * checking that. Down the road this should use space(16).
7196 		 */
7197 		if ((SPACE_CNT(count) > 0x7fffff) ||
7198 		    (SPACE_CNT(count) < -(0x7fffff))) {
7199 			un->un_sbuf_busy = 0;
7200 			cv_signal(&un->un_sbuf_cv);
7201 			return (EINVAL);
7202 		}
7203 		bp->b_bcount = count;
7204 		count = 0;
7205 		break;
7206 
7207 	case SCMD_RESERVE:
7208 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7209 		bp->b_bcount = 0;
7210 		count = 0;
7211 		break;
7212 
7213 	case SCMD_RELEASE:
7214 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7215 		bp->b_bcount = 0;
7216 		count = 0;
7217 		break;
7218 
7219 	case SCMD_LOAD:
7220 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7221 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7222 		bp->b_bcount = count;
7223 		count = 0;
7224 		break;
7225 
7226 	case SCMD_ERASE:
7227 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7228 		    "erase tape\n");
7229 		bp->b_bcount = 0;
7230 		count = 0;
7231 		break;
7232 
7233 	case SCMD_MODE_SENSE:
7234 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7235 		    "mode sense\n");
7236 		bp->b_flags |= B_READ;
7237 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7238 		break;
7239 
7240 	case SCMD_MODE_SELECT:
7241 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7242 		    "mode select\n");
7243 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7244 		break;
7245 
7246 	case SCMD_READ_BLKLIM:
7247 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7248 		    "read block limits\n");
7249 		bp->b_flags |= B_READ;
7250 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7251 		break;
7252 
7253 	case SCMD_TEST_UNIT_READY:
7254 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7255 		    "test unit ready\n");
7256 		bp->b_bcount = 0;
7257 		count = 0;
7258 		break;
7259 
7260 	case SCMD_DOORLOCK:
7261 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7262 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7263 		bp->b_bcount = count = 0;
7264 		break;
7265 
7266 	case SCMD_READ_POSITION:
7267 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7268 		    "read position\n");
7269 		switch (un->un_read_pos_type) {
7270 		case LONG_POS:
7271 			count = sizeof (tape_position_long_t);
7272 			break;
7273 		case EXT_POS:
7274 			count = min(count, sizeof (tape_position_ext_t));
7275 			break;
7276 		case SHORT_POS:
7277 			count = sizeof (tape_position_t);
7278 			break;
7279 		default:
7280 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7281 			    "Unknown read position type 0x%x in "
7282 			    "st_make_cmd()\n", un->un_read_pos_type);
7283 		}
7284 		bp->b_bcount = count;
7285 		bp->b_flags |= B_READ;
7286 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7287 		break;
7288 
7289 	default:
7290 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7291 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
7292 	}
7293 
7294 	mutex_exit(ST_MUTEX);
7295 
7296 	if (count > 0) {
7297 		/*
7298 		 * We're going to do actual I/O.
7299 		 * Set things up for physio.
7300 		 */
7301 		struct iovec aiov;
7302 		struct uio auio;
7303 		struct uio *uio = &auio;
7304 
7305 		bzero(&auio, sizeof (struct uio));
7306 		bzero(&aiov, sizeof (struct iovec));
7307 		aiov.iov_base = bp->b_un.b_addr;
7308 		aiov.iov_len = count;
7309 
7310 		uio->uio_iov = &aiov;
7311 		uio->uio_iovcnt = 1;
7312 		uio->uio_resid = aiov.iov_len;
7313 		uio->uio_segflg = UIO_SYSSPACE;
7314 
7315 		/*
7316 		 * Let physio do the rest...
7317 		 */
7318 		bp->b_forw = (struct buf *)(uintptr_t)com;
7319 		bp->b_back = NULL;
7320 		err = physio(st_strategy, bp, dev,
7321 		    (bp->b_flags & B_READ) ? B_READ : B_WRITE,
7322 		    st_minphys, uio);
7323 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7324 		    "st_cmd: physio returns %d\n", err);
7325 	} else {
7326 		/*
7327 		 * Mimic physio
7328 		 */
7329 		bp->b_forw = (struct buf *)(uintptr_t)com;
7330 		bp->b_back = NULL;
7331 		bp->b_edev = dev;
7332 		bp->b_dev = cmpdev(dev);
7333 		bp->b_blkno = 0;
7334 		bp->b_resid = 0;
7335 		(void) st_strategy(bp);
7336 		if (!wait) {
7337 			/*
7338 			 * This is an async command- the caller won't wait
7339 			 * and doesn't care about errors.
7340 			 */
7341 			mutex_enter(ST_MUTEX);
7342 			return (0);
7343 		}
7344 
7345 		/*
7346 		 * BugTraq #4260046
7347 		 * ----------------
7348 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7349 		 * unconditionally. The old comment said...
7350 		 *
7351 		 * "if strategy was flagged with  persistent errors, we would
7352 		 *  have an error here, and the bp would never be sent, so we
7353 		 *  don't want to wait on a bp that was never sent...or hang"
7354 		 *
7355 		 * The new rationale, courtesy of Chitrank...
7356 		 *
7357 		 * "we should unconditionally biowait() here because
7358 		 *  st_strategy() will do a biodone() in the persistent error
7359 		 *  case and the following biowait() will return immediately.
7360 		 *  If not, in the case of "errors after pkt alloc" in
7361 		 *  st_start(), we will not biowait here which will cause the
7362 		 *  next biowait() to return immediately which will cause
7363 		 *  us to send out the next command. In the case where both of
7364 		 *  these use the sbuf, when the first command completes we'll
7365 		 *  free the packet attached to sbuf and the same pkt will
7366 		 *  get freed again when we complete the second command.
7367 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7368 		 *  st_start() for the pkt alloc failure case because physio()
7369 		 *  does biowait() and will hang if we don't do biodone()"
7370 		 */
7371 
7372 		err = biowait(bp);
7373 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7374 		    "st_cmd: biowait returns %d\n", err);
7375 	}
7376 	mutex_enter(ST_MUTEX);
7377 
7378 	un->un_sbuf_busy = 0;
7379 
7380 	/*
7381 	 * If was a space command need to update logical block position.
7382 	 * If the command failed such that positioning is invalid, Don't
7383 	 * update the position as the user must do this to validate the
7384 	 * position for data protection.
7385 	 */
7386 	if ((com == SCMD_SPACE) && (un->un_pos.pmode != invalid)) {
7387 		uchar_t status = un->un_status;
7388 		(void) st_update_block_pos(un);
7389 		un->un_status = status;
7390 	}
7391 
7392 	cv_signal(&un->un_sbuf_cv);
7393 	return (err);
7394 }
7395 
7396 static int
7397 st_set_compression(struct scsi_tape *un)
7398 {
7399 	int rval;
7400 	int turn_compression_on;
7401 	minor_t minor;
7402 
7403 	ST_FUNC(ST_DEVINFO, st_set_compression);
7404 
7405 	/*
7406 	 * Drive either dosn't have compression or it is controlled with
7407 	 * special density codes. Return ENOTTY so caller
7408 	 * knows nothing was done.
7409 	 */
7410 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7411 		un->un_comp_page = 0;
7412 		return (ENOTTY);
7413 	}
7414 
7415 	/* set compression based on minor node opened */
7416 	minor = MT_DENSITY(un->un_dev);
7417 
7418 	/*
7419 	 * If this the compression density or
7420 	 * the drive has two densities and uses mode select for
7421 	 * control of compression turn on compression for MT_DENSITY2
7422 	 * as well.
7423 	 */
7424 	if ((minor == ST_COMPRESSION_DENSITY) ||
7425 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7426 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7427 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7428 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7429 
7430 		turn_compression_on = 1;
7431 	} else {
7432 		turn_compression_on = 0;
7433 	}
7434 
7435 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7436 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7437 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7438 
7439 	/*
7440 	 * Need to determine which page does the device use for compression.
7441 	 * First try the data compression page. If this fails try the device
7442 	 * configuration page
7443 	 */
7444 
7445 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7446 		rval = st_set_datacomp_page(un, turn_compression_on);
7447 		if (rval == EALREADY) {
7448 			return (rval);
7449 		}
7450 		if (rval != 0) {
7451 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7452 				/*
7453 				 * This device does not support data
7454 				 * compression page
7455 				 */
7456 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7457 			} else if (un->un_state >= ST_STATE_OPEN) {
7458 				un->un_pos.pmode = invalid;
7459 				rval = EIO;
7460 			} else {
7461 				rval = -1;
7462 			}
7463 		} else {
7464 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7465 		}
7466 	}
7467 
7468 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7469 		rval = st_set_devconfig_page(un, turn_compression_on);
7470 		if (rval == EALREADY) {
7471 			return (rval);
7472 		}
7473 		if (rval != 0) {
7474 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7475 				/*
7476 				 * This device does not support
7477 				 * compression at all advice the
7478 				 * user and unset ST_MODE_SEL_COMP
7479 				 */
7480 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7481 				un->un_comp_page = 0;
7482 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7483 				    "Device Does Not Support Compression\n");
7484 			} else if (un->un_state >= ST_STATE_OPEN) {
7485 				un->un_pos.pmode = invalid;
7486 				rval = EIO;
7487 			} else {
7488 				rval = -1;
7489 			}
7490 		}
7491 	}
7492 
7493 	return (rval);
7494 }
7495 
7496 /*
7497  * set or unset compression thru device configuration page.
7498  */
7499 static int
7500 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7501 {
7502 	unsigned char cflag;
7503 	int rval = 0;
7504 
7505 
7506 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7507 
7508 	ASSERT(mutex_owned(ST_MUTEX));
7509 	/*
7510 	 * Figure what to set compression flag to.
7511 	 */
7512 	if (compression_on) {
7513 		/* They have selected a compression node */
7514 		if (un->un_dp->type == ST_TYPE_FUJI) {
7515 			cflag = 0x84;   /* use EDRC */
7516 		} else {
7517 			cflag = ST_DEV_CONFIG_DEF_COMP;
7518 		}
7519 	} else {
7520 		cflag = ST_DEV_CONFIG_NO_COMP;
7521 	}
7522 
7523 	/*
7524 	 * If compression is already set the way it was requested.
7525 	 * And if this not the first time we has tried.
7526 	 */
7527 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7528 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7529 		return (EALREADY);
7530 	}
7531 
7532 	un->un_mspl->page.dev.comp_alg = cflag;
7533 	/*
7534 	 * need to send mode select even if correct compression is
7535 	 * already set since need to set density code
7536 	 */
7537 
7538 #ifdef STDEBUG
7539 	if ((st_debug & 0xf) >= 6) {
7540 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7541 		    "st_set_devconfig_page: sense data for mode select",
7542 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7543 	}
7544 #endif
7545 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7546 
7547 	return (rval);
7548 }
7549 
7550 /*
7551  * set/reset compression bit thru data compression page
7552  */
7553 static int
7554 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7555 {
7556 	int compression_on_already;
7557 	int rval = 0;
7558 
7559 
7560 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7561 
7562 	ASSERT(mutex_owned(ST_MUTEX));
7563 	/*
7564 	 * If drive is not capable of compression (at this time)
7565 	 * return EALREADY so caller doesn't think that this page
7566 	 * is not supported. This check is for drives that can
7567 	 * disable compression from the front panel or configuration.
7568 	 * I doubt that a drive that supports this page is not really
7569 	 * capable of compression.
7570 	 */
7571 	if (un->un_mspl->page.comp.dcc == 0) {
7572 		return (EALREADY);
7573 	}
7574 
7575 	/* See if compression currently turned on */
7576 	if (un->un_mspl->page.comp.dce) {
7577 		compression_on_already = 1;
7578 	} else {
7579 		compression_on_already = 0;
7580 	}
7581 
7582 	/*
7583 	 * If compression is already set the way it was requested.
7584 	 * And if this not the first time we has tried.
7585 	 */
7586 	if ((compression_on == compression_on_already) &&
7587 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7588 		return (EALREADY);
7589 	}
7590 
7591 	/*
7592 	 * if we are already set to the appropriate compression
7593 	 * mode, don't set it again
7594 	 */
7595 	if (compression_on) {
7596 		/* compression selected */
7597 		un->un_mspl->page.comp.dce = 1;
7598 	} else {
7599 		un->un_mspl->page.comp.dce = 0;
7600 	}
7601 
7602 
7603 #ifdef STDEBUG
7604 	if ((st_debug & 0xf) >= 6) {
7605 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7606 		    "st_set_datacomp_page: sense data for mode select",
7607 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7608 	}
7609 #endif
7610 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7611 
7612 	return (rval);
7613 }
7614 
7615 static int
7616 st_modesense(struct scsi_tape *un)
7617 {
7618 	int rval;
7619 	uchar_t page;
7620 
7621 	ST_FUNC(ST_DEVINFO, st_modesense);
7622 
7623 	page = un->un_comp_page;
7624 
7625 	switch (page) {
7626 	case ST_DEV_DATACOMP_PAGE:
7627 	case ST_DEV_CONFIG_PAGE: /* fall through */
7628 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7629 		    sizeof (struct seq_mode));
7630 		break;
7631 
7632 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7633 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7634 			page = ST_DEV_DATACOMP_PAGE;
7635 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7636 			    sizeof (struct seq_mode));
7637 			if (rval == 0 && un->un_mspl->page_code == page) {
7638 				un->un_comp_page = page;
7639 				break;
7640 			}
7641 			page = ST_DEV_CONFIG_PAGE;
7642 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7643 			    sizeof (struct seq_mode));
7644 			if (rval == 0 && un->un_mspl->page_code == page) {
7645 				un->un_comp_page = page;
7646 				break;
7647 			}
7648 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7649 			un->un_comp_page = 0;
7650 		} else {
7651 			un->un_comp_page = 0;
7652 		}
7653 
7654 	default:	/* fall through */
7655 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7656 	}
7657 	return (rval);
7658 }
7659 
7660 static int
7661 st_modeselect(struct scsi_tape *un)
7662 {
7663 	int rval = 0;
7664 	int ix;
7665 
7666 	ST_FUNC(ST_DEVINFO, st_modeselect);
7667 
7668 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7669 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7670 	    un->un_dev, un->un_mspl->density);
7671 
7672 	ASSERT(mutex_owned(ST_MUTEX));
7673 
7674 	/*
7675 	 * The parameter list should be the same for all of the
7676 	 * cases that follow so set them here
7677 	 *
7678 	 * Try mode select first if if fails set fields manually
7679 	 */
7680 	rval = st_modesense(un);
7681 	if (rval != 0) {
7682 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7683 		    "st_modeselect: First mode sense failed\n");
7684 		un->un_mspl->bd_len  = 8;
7685 		un->un_mspl->high_nb = 0;
7686 		un->un_mspl->mid_nb  = 0;
7687 		un->un_mspl->low_nb  = 0;
7688 	}
7689 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7690 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7691 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7692 
7693 
7694 	/*
7695 	 * If configured to use a specific density code for a media type.
7696 	 * curdens is previously set by the minor node opened.
7697 	 * If the media type doesn't match the minor node we change it so it
7698 	 * looks like the correct one was opened.
7699 	 */
7700 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7701 		uchar_t best;
7702 
7703 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7704 			if (un->un_mspl->media_type ==
7705 			    un->un_dp->mediatype[ix]) {
7706 				best = ix;
7707 				/*
7708 				 * It matches but it might not be the only one.
7709 				 * Use the highest matching media type but not
7710 				 * to exceed the density selected by the open.
7711 				 */
7712 				if (ix < un->un_curdens) {
7713 					continue;
7714 				}
7715 				un->un_curdens = ix;
7716 				break;
7717 			}
7718 		}
7719 		/* If a match was found best will not be 0xff any more */
7720 		if (best < NDENSITIES) {
7721 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7722 			    "found media 0x%X using density 0x%X\n",
7723 			    un->un_mspl->media_type,
7724 			    un->un_dp->densities[best]);
7725 			un->un_mspl->density = un->un_dp->densities[best];
7726 		} else {
7727 			/* Otherwise set density based on minor node opened */
7728 			un->un_mspl->density =
7729 			    un->un_dp->densities[un->un_curdens];
7730 		}
7731 	} else {
7732 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7733 	}
7734 
7735 	if (un->un_dp->options & ST_NOBUF) {
7736 		un->un_mspl->bufm = 0;
7737 	} else {
7738 		un->un_mspl->bufm = 1;
7739 	}
7740 
7741 	rval = st_set_compression(un);
7742 
7743 	/*
7744 	 * If st_set_compression returned invalid or already it
7745 	 * found no need to do the mode select.
7746 	 * So do it here.
7747 	 */
7748 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7749 
7750 		/* Zero non-writeable fields */
7751 		un->un_mspl->data_len = 0;
7752 		un->un_mspl->media_type = 0;
7753 		un->un_mspl->wp = 0;
7754 
7755 		/* need to set the density code */
7756 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7757 		if (rval != 0) {
7758 			if (un->un_state >= ST_STATE_OPEN) {
7759 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7760 				    "unable to set tape mode\n");
7761 				un->un_pos.pmode = invalid;
7762 				rval = EIO;
7763 			} else {
7764 				rval = -1;
7765 			}
7766 		}
7767 	}
7768 
7769 	/*
7770 	 * The spec recommends to send a mode sense after a mode select
7771 	 */
7772 	(void) st_modesense(un);
7773 
7774 	ASSERT(mutex_owned(ST_MUTEX));
7775 
7776 	return (rval);
7777 }
7778 
7779 /*
7780  * st_gen_mode_sense
7781  *
7782  * generic mode sense.. it allows for any page
7783  */
7784 static int
7785 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7786     int page_size)
7787 {
7788 
7789 	int r;
7790 	char	cdb[CDB_GROUP0];
7791 	struct uscsi_cmd *com;
7792 
7793 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
7794 
7795 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7796 
7797 	bzero(cdb, CDB_GROUP0);
7798 	cdb[0] = SCMD_MODE_SENSE;
7799 	cdb[2] = (char)page;
7800 	cdb[4] = (char)page_size;
7801 
7802 	com->uscsi_cdb = cdb;
7803 	com->uscsi_cdblen = CDB_GROUP0;
7804 	com->uscsi_bufaddr = (caddr_t)page_data;
7805 	com->uscsi_buflen = page_size;
7806 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7807 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7808 
7809 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7810 	kmem_free(com, sizeof (*com));
7811 	return (r);
7812 }
7813 
7814 /*
7815  * st_gen_mode_select
7816  *
7817  * generic mode select.. it allows for any page
7818  */
7819 static int
7820 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7821     int page_size)
7822 {
7823 
7824 	int r;
7825 	char cdb[CDB_GROUP0];
7826 	struct uscsi_cmd *com;
7827 
7828 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
7829 
7830 	/* Zero non-writeable fields */
7831 	page_data->data_len = 0;
7832 	page_data->media_type = 0;
7833 	page_data->wp = 0;
7834 
7835 	/*
7836 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7837 	 */
7838 	if (page_size > MSIZE) {
7839 		page_data->ps = 0;
7840 	}
7841 
7842 
7843 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7844 
7845 	/*
7846 	 * then, do a mode select to set what ever info
7847 	 */
7848 	bzero(cdb, CDB_GROUP0);
7849 	cdb[0] = SCMD_MODE_SELECT;
7850 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7851 	cdb[4] = (char)page_size;
7852 
7853 	com->uscsi_cdb = cdb;
7854 	com->uscsi_cdblen = CDB_GROUP0;
7855 	com->uscsi_bufaddr = (caddr_t)page_data;
7856 	com->uscsi_buflen = page_size;
7857 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7858 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
7859 
7860 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7861 
7862 	kmem_free(com, sizeof (*com));
7863 	return (r);
7864 }
7865 
7866 static int
7867 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
7868 {
7869 	int rval;
7870 	char cdb[CDB_GROUP0];
7871 	struct uscsi_cmd *com;
7872 
7873 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
7874 
7875 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7876 
7877 	bzero(cdb, CDB_GROUP0);
7878 	cdb[0] = SCMD_READ_BLKLIM;
7879 
7880 	com->uscsi_cdb = cdb;
7881 	com->uscsi_cdblen = CDB_GROUP0;
7882 	com->uscsi_bufaddr = (caddr_t)read_blk;
7883 	com->uscsi_buflen = sizeof (struct read_blklim);
7884 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7885 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7886 
7887 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7888 	if (com->uscsi_status || com->uscsi_resid) {
7889 		rval = -1;
7890 	}
7891 
7892 	kmem_free(com, sizeof (*com));
7893 	return (rval);
7894 }
7895 
7896 static int
7897 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
7898     size_t buflen)
7899 {
7900 	int rval;
7901 	char cdb[CDB_GROUP1];
7902 	struct uscsi_cmd *com;
7903 
7904 	ST_FUNC(ST_DEVINFO, st_report_density_support);
7905 
7906 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7907 
7908 	bzero(cdb, CDB_GROUP1);
7909 	cdb[0] = SCMD_REPORT_DENSITIES;
7910 	cdb[7] = (buflen & 0xff00) >> 8;
7911 	cdb[8] = buflen & 0xff;
7912 
7913 	com->uscsi_cdb = cdb;
7914 	com->uscsi_cdblen = CDB_GROUP1;
7915 	com->uscsi_bufaddr = (caddr_t)density_data;
7916 	com->uscsi_buflen = buflen;
7917 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7918 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7919 
7920 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7921 	if (com->uscsi_status || com->uscsi_resid) {
7922 		rval = -1;
7923 	}
7924 
7925 	kmem_free(com, sizeof (*com));
7926 	return (rval);
7927 }
7928 
7929 static int
7930 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
7931     uchar_t option_code, ushort_t service_action)
7932 {
7933 	int rval;
7934 	char cdb[CDB_GROUP5];
7935 	struct uscsi_cmd *com;
7936 	uint32_t allo_length;
7937 
7938 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
7939 
7940 	allo_length = sizeof (struct one_com_des) +
7941 	    sizeof (struct com_timeout_des);
7942 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7943 
7944 	bzero(cdb, CDB_GROUP5);
7945 	cdb[0] = (char)SCMD_REPORT_TARGET_PORT_GROUPS;
7946 	cdb[1] = 0x0c; /* service action */
7947 	if (service_action) {
7948 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
7949 		cdb[4] = (service_action & 0xff00) >> 8;
7950 		cdb[5] = service_action & 0xff;
7951 	} else {
7952 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
7953 		    0x80); /* RCTD */
7954 	}
7955 	cdb[3] = option_code;
7956 	cdb[6] = (allo_length & 0xff000000) >> 24;
7957 	cdb[7] = (allo_length & 0xff0000) >> 16;
7958 	cdb[8] = (allo_length & 0xff00) >> 8;
7959 	cdb[9] = allo_length & 0xff;
7960 
7961 	com->uscsi_cdb = cdb;
7962 	com->uscsi_cdblen = CDB_GROUP5;
7963 	com->uscsi_bufaddr = (caddr_t)oper_data;
7964 	com->uscsi_buflen = allo_length;
7965 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7966 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7967 
7968 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7969 	if (com->uscsi_status) {
7970 		rval = -1;
7971 	}
7972 
7973 	kmem_free(com, sizeof (*com));
7974 	return (rval);
7975 }
7976 
7977 /*
7978  * Changes devices blocksize and bsize to requested blocksize nblksz.
7979  * Returns returned value from first failed call or zero on success.
7980  */
7981 static int
7982 st_change_block_size(dev_t dev, uint32_t nblksz)
7983 {
7984 	struct seq_mode *current;
7985 	int rval;
7986 	uint32_t oldblksz;
7987 
7988 	GET_SOFT_STATE(dev);
7989 
7990 	ST_FUNC(ST_DEVINFO, st_change_block_size);
7991 
7992 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7993 
7994 	/* Read current settings */
7995 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7996 	if (rval != 0) {
7997 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7998 		    "mode sense for change block size failed: rval = %d", rval);
7999 		goto finish;
8000 	}
8001 
8002 	/* Figure the current block size */
8003 	oldblksz =
8004 	    (current->high_bl << 16) |
8005 	    (current->mid_bl << 8) |
8006 	    (current->low_bl);
8007 
8008 	/* If current block size is the same as requested were done */
8009 	if (oldblksz == nblksz) {
8010 		un->un_bsize = nblksz;
8011 		rval = 0;
8012 		goto finish;
8013 	}
8014 
8015 	/* Change to requested block size */
8016 	current->high_bl = (uchar_t)(nblksz >> 16);
8017 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8018 	current->low_bl  = (uchar_t)(nblksz);
8019 
8020 	/* Attempt to change block size */
8021 	rval = st_gen_mode_select(un, current, MSIZE);
8022 	if (rval != 0) {
8023 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8024 		    "Set new block size failed: rval = %d", rval);
8025 		goto finish;
8026 	}
8027 
8028 	/* Read back and verify setting */
8029 	rval = st_modesense(un);
8030 	if (rval == 0) {
8031 		un->un_bsize =
8032 		    (un->un_mspl->high_bl << 16) |
8033 		    (un->un_mspl->mid_bl << 8) |
8034 		    (un->un_mspl->low_bl);
8035 
8036 		if (un->un_bsize != nblksz) {
8037 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8038 			    "Blocksize set does not equal requested blocksize"
8039 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8040 			rval = EIO;
8041 		}
8042 	}
8043 finish:
8044 	kmem_free(current, MSIZE);
8045 	return (rval);
8046 }
8047 
8048 
8049 static void
8050 st_init(struct scsi_tape *un)
8051 {
8052 	ST_FUNC(ST_DEVINFO, st_init);
8053 
8054 	ASSERT(mutex_owned(ST_MUTEX));
8055 
8056 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8057 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8058 	    un->un_dev);
8059 
8060 	un->un_pos.blkno = 0;
8061 	un->un_pos.fileno = 0;
8062 	un->un_lastop = ST_OP_NIL;
8063 	un->un_pos.eof = ST_NO_EOF;
8064 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8065 	if (st_error_level != SCSI_ERR_ALL) {
8066 		if (DEBUGGING) {
8067 			st_error_level = SCSI_ERR_ALL;
8068 		} else {
8069 			st_error_level = SCSI_ERR_RETRYABLE;
8070 		}
8071 	}
8072 }
8073 
8074 
8075 static void
8076 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8077 {
8078 	struct scsi_pkt *pkt;
8079 	struct uscsi_cmd *ucmd;
8080 	int count, tval = 0;
8081 	uint_t addr = 0;
8082 	int flags = 0;
8083 	int cdb_len = CDB_GROUP0; /* default */
8084 	uchar_t com;
8085 	char fixbit;
8086 
8087 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8088 
8089 	ASSERT(mutex_owned(ST_MUTEX));
8090 
8091 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8092 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8093 
8094 
8095 	/*
8096 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8097 	 * Length Indicator bits on read/write commands, for setting
8098 	 * the Long bit on erase commands, and for setting the Code
8099 	 * Field bits on space commands.
8100 	 * XXX why do we set lastop here?
8101 	 */
8102 
8103 	if (bp != un->un_sbufp) {		/* regular raw I/O */
8104 		int stat_size = (un->un_arq_enabled ?
8105 		    sizeof (struct scsi_arq_status) : 1);
8106 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8107 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
8108 		if (pkt == NULL) {
8109 			goto exit;
8110 		}
8111 		SET_BP_PKT(bp, pkt);
8112 		if (un->un_bsize == 0) {
8113 			count = bp->b_bcount;
8114 			fixbit = 0;
8115 		} else {
8116 			count = bp->b_bcount / un->un_bsize;
8117 			fixbit = 1;
8118 		}
8119 		if (bp->b_flags & B_READ) {
8120 			com = SCMD_READ;
8121 			un->un_lastop = ST_OP_READ;
8122 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8123 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8124 				fixbit = 2;
8125 			}
8126 		} else {
8127 			com = SCMD_WRITE;
8128 			un->un_lastop = ST_OP_WRITE;
8129 		}
8130 
8131 		tval = un->un_dp->io_timeout;
8132 
8133 		/*
8134 		 * For really large xfers, increase timeout
8135 		 */
8136 		if (bp->b_bcount > (10 * ONE_MEG))
8137 			tval *= bp->b_bcount/(10 * ONE_MEG);
8138 
8139 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8140 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8141 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8142 
8143 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8144 		/*
8145 		 * uscsi - build command, allocate scsi resources
8146 		 */
8147 		st_make_uscsi_cmd(un, ucmd, bp, func);
8148 		goto exit;
8149 
8150 	} else {				/* special I/O */
8151 		int stat_size = (un->un_arq_enabled ?
8152 		    sizeof (struct scsi_arq_status) : 1);
8153 		struct buf *allocbp = NULL;
8154 		com = (uchar_t)(uintptr_t)bp->b_forw;
8155 		count = bp->b_bcount;
8156 
8157 		switch (com) {
8158 		case SCMD_READ:
8159 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8160 			    "special read %d\n", count);
8161 			if (un->un_bsize == 0) {
8162 				fixbit = 2;	/* suppress SILI */
8163 			} else {
8164 				fixbit = 1;	/* Fixed Block Mode */
8165 				count /= un->un_bsize;
8166 			}
8167 			allocbp = bp;
8168 			un->un_lastop = ST_OP_READ;
8169 			tval = un->un_dp->io_timeout;
8170 			break;
8171 
8172 		case SCMD_WRITE:
8173 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8174 			    "special write %d\n", count);
8175 			if (un->un_bsize != 0) {
8176 				fixbit = 1;	/* Fixed Block Mode */
8177 				count /= un->un_bsize;
8178 			} else {
8179 				fixbit = 0;
8180 			}
8181 			allocbp = bp;
8182 			un->un_lastop = ST_OP_WRITE;
8183 			tval = un->un_dp->io_timeout;
8184 			break;
8185 
8186 		case SCMD_WRITE_FILE_MARK:
8187 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8188 			    "write %d file marks\n", count);
8189 			un->un_lastop = ST_OP_WEOF;
8190 			fixbit = 0;
8191 			tval = un->un_dp->io_timeout;
8192 			break;
8193 
8194 		case SCMD_REWIND:
8195 			if (bp->b_flags & B_ASYNC) {
8196 				fixbit = 1;
8197 			} else {
8198 				fixbit = 0;
8199 			}
8200 			count = 0;
8201 			un->un_lastop = ST_OP_CTL;
8202 			tval = un->un_dp->rewind_timeout;
8203 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8204 			    "rewind\n");
8205 			break;
8206 
8207 		case SCMD_SPACE:
8208 			fixbit = SPACE_TYPE(count);
8209 			count = (int)SPACE_CNT(count);
8210 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8211 			    "space %s %d from file %d blk %d\n",
8212 			    space_strs[fixbit & 7], count,
8213 			    un->un_pos.fileno, un->un_pos.blkno);
8214 			un->un_lastop = ST_OP_CTL;
8215 			tval = un->un_dp->space_timeout;
8216 			break;
8217 
8218 		case SCMD_LOAD:
8219 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8220 			    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
8221 			fixbit = 0;
8222 
8223 			/* Loading or Unloading */
8224 			if (count & LD_LOAD) {
8225 				tval = un->un_dp->load_timeout;
8226 			} else {
8227 				tval = un->un_dp->unload_timeout;
8228 			}
8229 			/* Is Retension requested */
8230 			if (count & LD_RETEN) {
8231 				tval += un->un_dp->rewind_timeout;
8232 			}
8233 			un->un_lastop = ST_OP_CTL;
8234 			break;
8235 
8236 		case SCMD_ERASE:
8237 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8238 			    "erase tape\n");
8239 			count = 0;
8240 			/*
8241 			 * We support long erase only
8242 			 */
8243 			fixbit = 1;
8244 			tval = un->un_dp->erase_timeout;
8245 			un->un_lastop = ST_OP_CTL;
8246 			break;
8247 
8248 		case SCMD_MODE_SENSE:
8249 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8250 			    "mode sense\n");
8251 			allocbp = bp;
8252 			fixbit = 0;
8253 			tval = un->un_dp->non_motion_timeout;
8254 			un->un_lastop = ST_OP_CTL;
8255 			break;
8256 
8257 		case SCMD_MODE_SELECT:
8258 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8259 			    "mode select\n");
8260 			allocbp = bp;
8261 			fixbit = 0;
8262 			tval = un->un_dp->non_motion_timeout;
8263 			un->un_lastop = ST_OP_CTL;
8264 			break;
8265 
8266 		case SCMD_RESERVE:
8267 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8268 			    "reserve\n");
8269 			fixbit = 0;
8270 			tval = un->un_dp->non_motion_timeout;
8271 			un->un_lastop = ST_OP_CTL;
8272 			break;
8273 
8274 		case SCMD_RELEASE:
8275 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8276 			    "release\n");
8277 			fixbit = 0;
8278 			tval = un->un_dp->non_motion_timeout;
8279 			un->un_lastop = ST_OP_CTL;
8280 			break;
8281 
8282 		case SCMD_READ_BLKLIM:
8283 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8284 			    "read block limits\n");
8285 			allocbp = bp;
8286 			fixbit = count = 0;
8287 			tval = un->un_dp->non_motion_timeout;
8288 			un->un_lastop = ST_OP_CTL;
8289 			break;
8290 
8291 		case SCMD_TEST_UNIT_READY:
8292 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8293 			    "test unit ready\n");
8294 			fixbit = 0;
8295 			tval = un->un_dp->non_motion_timeout;
8296 			un->un_lastop = ST_OP_CTL;
8297 			break;
8298 
8299 		case SCMD_DOORLOCK:
8300 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8301 			    "prevent/allow media removal\n");
8302 			fixbit = 0;
8303 			tval = un->un_dp->non_motion_timeout;
8304 			un->un_lastop = ST_OP_CTL;
8305 			break;
8306 
8307 		case SCMD_READ_POSITION:
8308 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8309 			    "read position\n");
8310 			fixbit = un->un_read_pos_type;
8311 			cdb_len = CDB_GROUP1;
8312 			tval = un->un_dp->non_motion_timeout;
8313 			allocbp = bp;
8314 			un->un_lastop = ST_OP_CTL;
8315 			switch (un->un_read_pos_type) {
8316 			case LONG_POS:
8317 				count = 0;
8318 				break;
8319 			case EXT_POS:
8320 				count = sizeof (tape_position_ext_t);
8321 				break;
8322 			case SHORT_POS:
8323 				count = 0;
8324 				break;
8325 			default:
8326 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8327 				    "Unknown read position type 0x%x in "
8328 				    " st_make_cmd()\n", un->un_read_pos_type);
8329 			}
8330 			break;
8331 
8332 		default:
8333 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8334 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8335 			    com);
8336 		}
8337 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8338 		    0, 0, func, (caddr_t)un);
8339 		if (pkt == NULL) {
8340 			goto exit;
8341 		}
8342 		if (allocbp) {
8343 			ASSERT(geterror(allocbp) == 0);
8344 		}
8345 
8346 	}
8347 
8348 
8349 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8350 	    com, addr, (uint_t)count, 0);
8351 	FILL_SCSI1_LUN(un->un_sd, pkt);
8352 	/*
8353 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8354 	 */
8355 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8356 	pkt->pkt_flags = flags;
8357 
8358 #ifdef STDEBUG
8359 	if ((st_debug & 0xf) >= 6) {
8360 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8361 		    "cmd cdb", (char *)pkt->pkt_cdbp, cdb_len);
8362 	}
8363 #endif
8364 
8365 	/*
8366 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8367 	 * device, set the Vendor Unique bit to
8368 	 * write Short File Mark.
8369 	 */
8370 	if (com == SCMD_WRITE_FILE_MARK &&
8371 	    un->un_dp->options & ST_SHORT_FILEMARKS) {
8372 		switch (un->un_dp->type) {
8373 		case ST_TYPE_EXB8500:
8374 		case ST_TYPE_EXABYTE:
8375 			/*
8376 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8377 			 * is set to to write Short File Mark
8378 			 */
8379 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
8380 			break;
8381 
8382 		default:
8383 			/*
8384 			 * Well, if ST_SHORT_FILEMARKS is set for other
8385 			 * tape drives, it is just ignored
8386 			 */
8387 			break;
8388 		}
8389 	}
8390 	ASSERT(tval);
8391 	pkt->pkt_time = tval;
8392 	pkt->pkt_comp = st_intr;
8393 	pkt->pkt_private = (opaque_t)bp;
8394 
8395 	SET_BP_PKT(bp, pkt);
8396 
8397 exit:
8398 	ASSERT(mutex_owned(ST_MUTEX));
8399 }
8400 
8401 
8402 /*
8403  * Build a command based on a uscsi command;
8404  */
8405 static void
8406 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8407     struct buf *bp, int (*func)(caddr_t))
8408 {
8409 	struct scsi_pkt *pkt;
8410 	caddr_t cdb;
8411 	int	cdblen;
8412 	int stat_size;
8413 
8414 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8415 
8416 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8417 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8418 
8419 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8420 		stat_size = (un->un_arq_enabled ?
8421 		    sizeof (struct scsi_arq_status) : 1);
8422 	} else {
8423 		stat_size = 1;
8424 	}
8425 
8426 	ASSERT(mutex_owned(ST_MUTEX));
8427 
8428 	cdb = ucmd->uscsi_cdb;
8429 	cdblen = ucmd->uscsi_cdblen;
8430 
8431 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8432 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8433 	    ucmd->uscsi_buflen, bp->b_bcount);
8434 	pkt = scsi_init_pkt(ROUTE, NULL,
8435 	    (bp->b_bcount > 0) ? bp : NULL,
8436 	    cdblen, stat_size, 0, 0, func, (caddr_t)un);
8437 	if (pkt == NULL) {
8438 		goto exit;
8439 	}
8440 
8441 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8442 
8443 #ifdef STDEBUG
8444 	if ((st_debug & 0xf) >= 6) {
8445 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8446 		    "pkt_cdbp", (char *)cdb, cdblen);
8447 	}
8448 #endif
8449 
8450 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8451 		pkt->pkt_flags |= FLAG_SILENT;
8452 	}
8453 
8454 	pkt->pkt_time = ucmd->uscsi_timeout;
8455 	pkt->pkt_comp = st_intr;
8456 	pkt->pkt_private = (opaque_t)bp;
8457 
8458 	SET_BP_PKT(bp, pkt);
8459 exit:
8460 	ASSERT(mutex_owned(ST_MUTEX));
8461 }
8462 
8463 
8464 /*
8465  * restart cmd currently at the head of the runq
8466  *
8467  * If scsi_transport() succeeds or the retries
8468  * count exhausted, restore the throttle that was
8469  * zeroed out in st_handle_intr_busy().
8470  *
8471  */
8472 static void
8473 st_intr_restart(void *arg)
8474 {
8475 	struct scsi_tape *un = arg;
8476 	struct buf *bp;
8477 	int status = TRAN_ACCEPT;
8478 
8479 	mutex_enter(ST_MUTEX);
8480 
8481 	ST_FUNC(ST_DEVINFO, st_intr_restart);
8482 
8483 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8484 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
8485 
8486 	un->un_hib_tid = 0;
8487 
8488 	/*
8489 	 * move from waitq to runq, if there is anything on the waitq
8490 	 */
8491 	if ((bp = un->un_quef) == NULL) {
8492 		mutex_exit(ST_MUTEX);
8493 		return;
8494 	}
8495 
8496 	/*
8497 	 * Here we know :
8498 	 *	throttle = 0, via st_handle_intr_busy
8499 	 */
8500 
8501 	if (un->un_quel == bp) {
8502 		un->un_quel = NULL;
8503 		un->un_quef = NULL;	/* we know it's the first one */
8504 	} else {
8505 		un->un_quef = bp->b_actf;
8506 	}
8507 	bp->b_actf = NULL;
8508 
8509 	if (un->un_runqf) {
8510 		/*
8511 		 * not good, we don't want to requeue something after
8512 		 * another.
8513 		 */
8514 		mutex_exit(ST_MUTEX);
8515 		goto done_error;
8516 	} else {
8517 		un->un_runqf = bp;
8518 		un->un_runql = bp;
8519 	}
8520 
8521 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8522 
8523 	mutex_exit(ST_MUTEX);
8524 
8525 	status = scsi_transport(BP_PKT(bp));
8526 
8527 	mutex_enter(ST_MUTEX);
8528 
8529 	if (status != TRAN_ACCEPT) {
8530 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8531 		mutex_exit(ST_MUTEX);
8532 
8533 		if (status == TRAN_BUSY) {
8534 			if (st_handle_intr_busy(un, bp,
8535 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8536 				return;	/* timeout is setup again */
8537 		}
8538 
8539 	} else {
8540 		un->un_tran_retry_ct = 0;
8541 		if (un->un_last_throttle) {
8542 			un->un_throttle = un->un_last_throttle;
8543 		}
8544 		mutex_exit(ST_MUTEX);
8545 		return;
8546 	}
8547 
8548 done_error:
8549 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8550 	    "restart transport rejected\n");
8551 	bp->b_resid = bp->b_bcount;
8552 
8553 #ifndef __lock_lint
8554 	/*
8555 	 * warlock doesn't understand this potential
8556 	 * recursion?
8557 	 */
8558 	mutex_enter(ST_MUTEX);
8559 	if (un->un_last_throttle) {
8560 		un->un_throttle = un->un_last_throttle;
8561 	}
8562 	if (status != TRAN_ACCEPT)
8563 		ST_DO_ERRSTATS(un, st_transerrs);
8564 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8565 	SET_PE_FLAG(un);
8566 	st_bioerror(bp, EIO);
8567 	st_done_and_mutex_exit(un, bp);
8568 #endif
8569 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8570 	    "busy restart aborted\n");
8571 }
8572 
8573 /*
8574  * st_check_media():
8575  * Periodically check the media state using scsi_watch service;
8576  * this service calls back after TUR and possibly request sense
8577  * the callback handler (st_media_watch_cb()) decodes the request sense
8578  * data (if any)
8579  */
8580 
8581 static int
8582 st_check_media(dev_t dev, enum mtio_state state)
8583 {
8584 	int rval = 0;
8585 	enum mtio_state	prev_state;
8586 	opaque_t token = NULL;
8587 
8588 	GET_SOFT_STATE(dev);
8589 
8590 	ST_FUNC(ST_DEVINFO, st_check_media);
8591 
8592 	mutex_enter(ST_MUTEX);
8593 
8594 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8595 	    "st_check_media:state=%x, mediastate=%x\n",
8596 	    state, un->un_mediastate);
8597 
8598 	prev_state = un->un_mediastate;
8599 
8600 	/*
8601 	 * is there anything to do?
8602 	 */
8603 retry:
8604 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8605 		/*
8606 		 * submit the request to the scsi_watch service;
8607 		 * scsi_media_watch_cb() does the real work
8608 		 */
8609 		mutex_exit(ST_MUTEX);
8610 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8611 		    st_check_media_time, SENSE_LENGTH,
8612 		    st_media_watch_cb, (caddr_t)dev);
8613 		if (token == NULL) {
8614 			rval = EAGAIN;
8615 			goto done;
8616 		}
8617 		mutex_enter(ST_MUTEX);
8618 
8619 		un->un_swr_token = token;
8620 		un->un_specified_mediastate = state;
8621 
8622 		/*
8623 		 * now wait for media change
8624 		 * we will not be signalled unless mediastate == state but it
8625 		 * still better to test for this condition, since there
8626 		 * is a 5 sec cv_broadcast delay when
8627 		 *  mediastate == MTIO_INSERTED
8628 		 */
8629 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8630 		    "st_check_media:waiting for media state change\n");
8631 		while (un->un_mediastate == state) {
8632 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8633 				mutex_exit(ST_MUTEX);
8634 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8635 				    "st_check_media:waiting for media state "
8636 				    "was interrupted\n");
8637 				rval = EINTR;
8638 				goto done;
8639 			}
8640 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8641 			    "st_check_media:received signal, state=%x\n",
8642 			    un->un_mediastate);
8643 		}
8644 	}
8645 
8646 	/*
8647 	 * if we transitioned to MTIO_INSERTED, media has really been
8648 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8649 	 * Reset and retry the state change.  If everything is ok, replay
8650 	 * the open() logic.
8651 	 */
8652 	if ((un->un_mediastate == MTIO_INSERTED) &&
8653 	    (un->un_state == ST_STATE_OFFLINE)) {
8654 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8655 		    "st_check_media: calling st_cmd to confirm inserted\n");
8656 
8657 		/*
8658 		 * set this early so that TUR will make it through strategy
8659 		 * without triggering a st_tape_init().  We needed it set
8660 		 * before calling st_tape_init() ourselves anyway.  If TUR
8661 		 * fails, set it back
8662 		 */
8663 		un->un_state = ST_STATE_INITIALIZING;
8664 
8665 		/*
8666 		 * If not reserved fail as getting reservation conflict
8667 		 * will make this hang forever.
8668 		 */
8669 		if ((un->un_rsvd_status &
8670 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8671 			mutex_exit(ST_MUTEX);
8672 			rval = EACCES;
8673 			goto done;
8674 		}
8675 		rval = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
8676 		if (rval == EACCES) {
8677 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8678 			    "st_check_media: TUR got Reservation Conflict\n");
8679 			mutex_exit(ST_MUTEX);
8680 			goto done;
8681 		}
8682 		if (rval) {
8683 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8684 			    "st_check_media: TUR failed, going to retry\n");
8685 			un->un_mediastate = prev_state;
8686 			un->un_state = ST_STATE_OFFLINE;
8687 			goto retry;
8688 		}
8689 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8690 		    "st_check_media: media inserted\n");
8691 
8692 		/* this also rewinds the tape */
8693 		rval = st_tape_init(dev);
8694 		if (rval != 0) {
8695 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8696 			    "st_check_media : OFFLINE init failure ");
8697 			un->un_state = ST_STATE_OFFLINE;
8698 			un->un_pos.pmode = invalid;
8699 		} else {
8700 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8701 			un->un_pos.fileno = 0;
8702 			un->un_pos.blkno = 0;
8703 			un->un_pos.lgclblkno = 0;
8704 		}
8705 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8706 	    (un->un_state != ST_STATE_OFFLINE)) {
8707 		/*
8708 		 * supported devices must be rewound before ejection
8709 		 * rewind resets fileno & blkno
8710 		 */
8711 		un->un_laststate = un->un_state;
8712 		un->un_state = ST_STATE_OFFLINE;
8713 	}
8714 	mutex_exit(ST_MUTEX);
8715 done:
8716 	if (token) {
8717 		(void) scsi_watch_request_terminate(token,
8718 		    SCSI_WATCH_TERMINATE_WAIT);
8719 		mutex_enter(ST_MUTEX);
8720 		un->un_swr_token = (opaque_t)NULL;
8721 		mutex_exit(ST_MUTEX);
8722 	}
8723 
8724 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8725 
8726 	return (rval);
8727 }
8728 
8729 /*
8730  * st_media_watch_cb() is called by scsi_watch_thread for
8731  * verifying the request sense data (if any)
8732  */
8733 static int
8734 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8735 {
8736 	struct scsi_status *statusp = resultp->statusp;
8737 	struct scsi_extended_sense *sensep = resultp->sensep;
8738 	uchar_t actual_sense_length = resultp->actual_sense_length;
8739 	struct scsi_tape *un;
8740 	enum mtio_state state = MTIO_NONE;
8741 	int instance;
8742 	dev_t dev = (dev_t)arg;
8743 
8744 	instance = MTUNIT(dev);
8745 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8746 		return (-1);
8747 	}
8748 
8749 	mutex_enter(ST_MUTEX);
8750 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
8751 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8752 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8753 	    *((char *)statusp), (void *)sensep,
8754 	    actual_sense_length);
8755 
8756 
8757 	/*
8758 	 * if there was a check condition then sensep points to valid
8759 	 * sense data
8760 	 * if status was not a check condition but a reservation or busy
8761 	 * status then the new state is MTIO_NONE
8762 	 */
8763 	if (sensep) {
8764 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8765 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8766 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8767 
8768 		switch (un->un_dp->type) {
8769 		default:
8770 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8771 			    "st_media_watch_cb: unknown drive type %d, "
8772 			    "default to ST_TYPE_HP\n", un->un_dp->type);
8773 		/* FALLTHROUGH */
8774 
8775 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8776 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8777 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8778 			if (un->un_dp->type == ST_TYPE_FUJI) {
8779 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8780 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8781 			} else {
8782 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8783 				    "st_media_watch_cb: ST_TYPE_HP\n");
8784 			}
8785 			switch (sensep->es_key) {
8786 			case KEY_UNIT_ATTENTION:
8787 				/* not ready to ready transition */
8788 				/* hp/es_qual_code == 80 on>off>on */
8789 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8790 				if (sensep->es_add_code == 0x28) {
8791 					state = MTIO_INSERTED;
8792 				}
8793 				break;
8794 			case KEY_NOT_READY:
8795 				/* in process, rewinding or loading */
8796 				if ((sensep->es_add_code == 0x04) &&
8797 				    (sensep->es_qual_code == 0x00)) {
8798 					state = MTIO_EJECTED;
8799 				}
8800 				break;
8801 			}
8802 			break;
8803 
8804 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8805 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8806 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8807 			switch (sensep->es_key) {
8808 			case KEY_UNIT_ATTENTION:
8809 				/* operator medium removal request */
8810 				if ((sensep->es_add_code == 0x5a) &&
8811 				    (sensep->es_qual_code == 0x01)) {
8812 					state = MTIO_EJECTED;
8813 				/* not ready to ready transition */
8814 				} else if ((sensep->es_add_code == 0x28) &&
8815 				    (sensep->es_qual_code == 0x00)) {
8816 					state = MTIO_INSERTED;
8817 				}
8818 				break;
8819 			case KEY_NOT_READY:
8820 				/* medium not present */
8821 				if (sensep->es_add_code == 0x3a) {
8822 					state = MTIO_EJECTED;
8823 				}
8824 				break;
8825 			}
8826 			break;
8827 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8828 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8829 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8830 			switch (sensep->es_key) {
8831 			case KEY_NOT_READY:
8832 				if ((sensep->es_add_code == 0x04) &&
8833 				    (sensep->es_qual_code == 0x00)) {
8834 					/* volume not mounted? */
8835 					state = MTIO_EJECTED;
8836 				} else if (sensep->es_add_code == 0x3a) {
8837 					state = MTIO_EJECTED;
8838 				}
8839 				break;
8840 			case KEY_UNIT_ATTENTION:
8841 				state = MTIO_EJECTED;
8842 				break;
8843 			}
8844 			break;
8845 
8846 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8847 			switch (sensep->es_key) {
8848 			case KEY_UNIT_ATTENTION:
8849 				if (sensep->es_add_code == 0x28) {
8850 					state = MTIO_INSERTED;
8851 				}
8852 				break;
8853 			case KEY_NOT_READY:
8854 				if (sensep->es_add_code == 0x04) {
8855 					/* in transition but could be either */
8856 					state = un->un_specified_mediastate;
8857 				} else if ((sensep->es_add_code == 0x3a) &&
8858 				    (sensep->es_qual_code == 0x00)) {
8859 					state = MTIO_EJECTED;
8860 				}
8861 				break;
8862 			}
8863 			break;
8864 		}
8865 	} else if (*((char *)statusp) == STATUS_GOOD) {
8866 		state = MTIO_INSERTED;
8867 	}
8868 
8869 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8870 	    "st_media_watch_cb:state=%x, specified=%x\n",
8871 	    state, un->un_specified_mediastate);
8872 
8873 	/*
8874 	 * now signal the waiting thread if this is *not* the specified state;
8875 	 * delay the signal if the state is MTIO_INSERTED
8876 	 * to allow the target to recover
8877 	 */
8878 	if (state != un->un_specified_mediastate) {
8879 		un->un_mediastate = state;
8880 		if (state == MTIO_INSERTED) {
8881 			/*
8882 			 * delay the signal to give the drive a chance
8883 			 * to do what it apparently needs to do
8884 			 */
8885 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8886 			    "st_media_watch_cb:delayed cv_broadcast\n");
8887 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8888 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8889 		} else {
8890 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8891 			    "st_media_watch_cb:immediate cv_broadcast\n");
8892 			cv_broadcast(&un->un_state_cv);
8893 		}
8894 	}
8895 	mutex_exit(ST_MUTEX);
8896 	return (0);
8897 }
8898 
8899 /*
8900  * delayed cv_broadcast to allow for target to recover
8901  * from media insertion
8902  */
8903 static void
8904 st_delayed_cv_broadcast(void *arg)
8905 {
8906 	struct scsi_tape *un = arg;
8907 
8908 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
8909 
8910 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8911 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
8912 
8913 	mutex_enter(ST_MUTEX);
8914 	cv_broadcast(&un->un_state_cv);
8915 	mutex_exit(ST_MUTEX);
8916 }
8917 
8918 /*
8919  * restart cmd currently at the start of the waitq
8920  */
8921 static void
8922 st_start_restart(void *arg)
8923 {
8924 	struct scsi_tape *un = arg;
8925 
8926 	ST_FUNC(ST_DEVINFO, st_start_restart);
8927 
8928 	ASSERT(un != NULL);
8929 
8930 	mutex_enter(ST_MUTEX);
8931 
8932 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8933 	    "st_tran_restart()\n");
8934 
8935 	if (un->un_quef) {
8936 		st_start(un);
8937 	}
8938 
8939 	mutex_exit(ST_MUTEX);
8940 }
8941 
8942 
8943 /*
8944  * Command completion processing
8945  *
8946  */
8947 static void
8948 st_intr(struct scsi_pkt *pkt)
8949 {
8950 	struct scsi_tape *un;
8951 	struct buf *last_runqf;
8952 	struct buf *bp;
8953 	int action = COMMAND_DONE;
8954 	clock_t	timout;
8955 	int	status;
8956 
8957 
8958 	bp = pkt->pkt_private;
8959 
8960 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8961 
8962 	ST_FUNC(ST_DEVINFO, st_intr);
8963 
8964 	mutex_enter(ST_MUTEX);
8965 
8966 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8967 
8968 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8969 
8970 	if (pkt->pkt_reason != CMD_CMPLT) {
8971 
8972 		/* If device has gone away not much else to do */
8973 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8974 			action = COMMAND_DONE_ERROR;
8975 		} else if (un->un_state == ST_STATE_SENSING) {
8976 			ST_DO_ERRSTATS(un, st_transerrs);
8977 			action = COMMAND_DONE_ERROR;
8978 		} else {
8979 			action = st_handle_incomplete(un, bp);
8980 		}
8981 	/*
8982 	 * At this point we know that the command was successfully
8983 	 * completed. Now what?
8984 	 */
8985 	} else if (un->un_arq_enabled &&
8986 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8987 		/*
8988 		 * the transport layer successfully completed an autorqsense
8989 		 */
8990 		action = st_handle_autosense(un, bp);
8991 
8992 	} else if (un->un_state == ST_STATE_SENSING) {
8993 		/*
8994 		 * okay. We were running a REQUEST SENSE. Find
8995 		 * out what to do next.
8996 		 * some actions are based on un_state, hence
8997 		 * restore the state st was in before ST_STATE_SENSING.
8998 		 */
8999 		un->un_state = un->un_laststate;
9000 		action = st_handle_sense(un, bp);
9001 		/*
9002 		 * set pkt back to original packet in case we will have
9003 		 * to requeue it
9004 		 */
9005 		pkt = BP_PKT(bp);
9006 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
9007 		/*
9008 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9009 		 * to see if the status bits we're okay. If a request sense
9010 		 * is to be run, that will happen.
9011 		 */
9012 		action = st_check_error(un, pkt);
9013 	}
9014 
9015 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9016 		switch (action) {
9017 			case QUE_COMMAND:
9018 				/*
9019 				 * return cmd to head to the queue
9020 				 * since we are suspending so that
9021 				 * it gets restarted during resume
9022 				 */
9023 				if (un->un_runqf) {
9024 					last_runqf = un->un_runqf;
9025 					un->un_runqf = bp;
9026 					bp->b_actf = last_runqf;
9027 				} else {
9028 					bp->b_actf = NULL;
9029 					un->un_runqf = bp;
9030 					un->un_runql = bp;
9031 				}
9032 				action = JUST_RETURN;
9033 				break;
9034 
9035 			case QUE_SENSE:
9036 				action = COMMAND_DONE_ERROR;
9037 				break;
9038 
9039 			default:
9040 				break;
9041 		}
9042 	}
9043 
9044 	/*
9045 	 * Restore old state if we were sensing.
9046 	 */
9047 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9048 		un->un_state = un->un_laststate;
9049 	}
9050 
9051 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9052 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
9053 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
9054 
9055 
9056 	switch (action) {
9057 	case COMMAND_DONE_EACCES:
9058 		/* this is to report a reservation conflict */
9059 		st_bioerror(bp, EACCES);
9060 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9061 		    "Reservation Conflict \n");
9062 		un->un_pos.pmode = invalid;
9063 
9064 		/*FALLTHROUGH*/
9065 	case COMMAND_DONE_ERROR:
9066 		if (un->un_pos.eof < ST_EOT_PENDING &&
9067 		    un->un_state >= ST_STATE_OPEN) {
9068 			/*
9069 			 * all errors set state of the tape to 'unknown'
9070 			 * unless we're at EOT or are doing append testing.
9071 			 * If sense key was illegal request, preserve state.
9072 			 */
9073 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9074 				un->un_pos.pmode = invalid;
9075 			}
9076 		}
9077 
9078 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9079 		/*
9080 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9081 		 * make sure an error ocurrs, so make sure at least EIO is
9082 		 * returned
9083 		 */
9084 		if (geterror(bp) == 0)
9085 			st_bioerror(bp, EIO);
9086 
9087 		SET_PE_FLAG(un);
9088 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9089 		    (un->un_errno == EIO)) {
9090 			un->un_rqs_state &= ~(ST_RQS_VALID);
9091 		}
9092 		goto done;
9093 
9094 	case COMMAND_DONE_ERROR_RECOVERED:
9095 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9096 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9097 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9098 		if (geterror(bp) == 0) {
9099 			st_bioerror(bp, EIO);
9100 		}
9101 		SET_PE_FLAG(un);
9102 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9103 		    (un->un_errno == EIO)) {
9104 			un->un_rqs_state &= ~(ST_RQS_VALID);
9105 		}
9106 		/*FALLTHROUGH*/
9107 	case COMMAND_DONE:
9108 		st_set_state(un);
9109 done:
9110 		ST_DO_KSTATS(bp, kstat_runq_exit);
9111 		st_done_and_mutex_exit(un, bp);
9112 		return;
9113 
9114 	case QUE_SENSE:
9115 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9116 			goto sense_error;
9117 
9118 		if (un->un_state != ST_STATE_SENSING) {
9119 			un->un_laststate = un->un_state;
9120 			un->un_state = ST_STATE_SENSING;
9121 		}
9122 
9123 		un->un_rqs->pkt_private = (opaque_t)bp;
9124 		bzero(ST_RQSENSE, SENSE_LENGTH);
9125 
9126 		if (un->un_throttle) {
9127 			un->un_last_throttle = un->un_throttle;
9128 			un->un_throttle = 0;
9129 		}
9130 
9131 		mutex_exit(ST_MUTEX);
9132 
9133 		/*
9134 		 * never retry this, some other command will have nuked the
9135 		 * sense, anyway
9136 		 */
9137 		status = scsi_transport(un->un_rqs);
9138 
9139 		mutex_enter(ST_MUTEX);
9140 
9141 		if (un->un_last_throttle) {
9142 			un->un_throttle = un->un_last_throttle;
9143 		}
9144 
9145 		if (status == TRAN_ACCEPT) {
9146 			mutex_exit(ST_MUTEX);
9147 			return;
9148 		}
9149 		if (status != TRAN_BUSY)
9150 			ST_DO_ERRSTATS(un, st_transerrs);
9151 sense_error:
9152 		un->un_pos.pmode = invalid;
9153 		st_bioerror(bp, EIO);
9154 		SET_PE_FLAG(un);
9155 		goto done;
9156 
9157 	case QUE_BUSY_COMMAND:
9158 		/* longish timeout */
9159 		timout = ST_STATUS_BUSY_TIMEOUT;
9160 		goto que_it_up;
9161 
9162 	case QUE_COMMAND:
9163 		/* short timeout */
9164 		timout = ST_TRAN_BUSY_TIMEOUT;
9165 que_it_up:
9166 		/*
9167 		 * let st_handle_intr_busy put this bp back on waitq and make
9168 		 * checks to see if it is ok to requeue the command.
9169 		 */
9170 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9171 
9172 		/*
9173 		 * Save the throttle before setting up the timeout
9174 		 */
9175 		if (un->un_throttle) {
9176 			un->un_last_throttle = un->un_throttle;
9177 		}
9178 		mutex_exit(ST_MUTEX);
9179 		if (st_handle_intr_busy(un, bp, timout) == 0)
9180 			return;		/* timeout is setup again */
9181 
9182 		mutex_enter(ST_MUTEX);
9183 		un->un_pos.pmode = invalid;
9184 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9185 		st_bioerror(bp, EIO);
9186 		SET_PE_FLAG(un);
9187 		goto done;
9188 
9189 	case QUE_LAST_COMMAND:
9190 
9191 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9192 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9193 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9194 			goto last_command_error;
9195 		}
9196 		mutex_exit(ST_MUTEX);
9197 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9198 			return;
9199 		mutex_enter(ST_MUTEX);
9200 last_command_error:
9201 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9202 		un->un_pos.pmode = invalid;
9203 		st_bioerror(bp, EIO);
9204 		SET_PE_FLAG(un);
9205 		goto done;
9206 
9207 	case JUST_RETURN:
9208 	default:
9209 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9210 		mutex_exit(ST_MUTEX);
9211 		return;
9212 	}
9213 	/*NOTREACHED*/
9214 }
9215 
9216 static int
9217 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9218 {
9219 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9220 	int rval = COMMAND_DONE_ERROR;
9221 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9222 	    un->un_rqs : BP_PKT(bp);
9223 	int result;
9224 
9225 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9226 
9227 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9228 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9229 
9230 	ASSERT(mutex_owned(ST_MUTEX));
9231 
9232 	switch (pkt->pkt_reason) {
9233 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9234 		/*
9235 		 * this occurs when accessing a powered down drive, no
9236 		 * need to complain; just fail the open
9237 		 */
9238 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9239 
9240 		/*
9241 		 * if we have commands outstanding in HBA, and a command
9242 		 * comes back incomplete, we're hosed, so reset target
9243 		 * If we have the bus, but cmd_incomplete, we probably just
9244 		 * have a failed selection, so don't reset the target, just
9245 		 * requeue the command and try again
9246 		 */
9247 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9248 			goto reset_target;
9249 		}
9250 
9251 		/*
9252 		 * Retry selection a couple more times if we're
9253 		 * open.  If opening, we only try just once to
9254 		 * reduce probe time for nonexistant devices.
9255 		 */
9256 		if ((un->un_laststate > ST_STATE_OPENING) &&
9257 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
9258 			rval = QUE_COMMAND;
9259 		}
9260 		ST_DO_ERRSTATS(un, st_transerrs);
9261 		break;
9262 
9263 	case CMD_ABORTED:
9264 		/*
9265 		 * most likely this is caused by flush-on-error support. If
9266 		 * it was not there, the we're in trouble.
9267 		 */
9268 		if (!un->un_flush_on_errors) {
9269 			un->un_status = SUN_KEY_FATAL;
9270 			goto reset_target;
9271 		}
9272 
9273 		st_set_pe_errno(un);
9274 		bioerror(bp, un->un_errno);
9275 		if (un->un_errno)
9276 			return (COMMAND_DONE_ERROR);
9277 		else
9278 			return (COMMAND_DONE);
9279 
9280 	case CMD_TIMEOUT:	/* Command timed out */
9281 		un->un_status = SUN_KEY_TIMEOUT;
9282 
9283 		/*FALLTHROUGH*/
9284 	default:
9285 reset_target:
9286 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9287 		    "transport completed with %s\n",
9288 		    scsi_rname(pkt->pkt_reason));
9289 		ST_DO_ERRSTATS(un, st_transerrs);
9290 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9291 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9292 		    STAT_ABORTED)) == 0)) {
9293 
9294 			/*
9295 			 * If we haven't reserved the drive don't reset it.
9296 			 */
9297 			if ((un->un_rsvd_status &
9298 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9299 				return (rval);
9300 			}
9301 
9302 			/*
9303 			 * if we aren't lost yet we will be soon.
9304 			 */
9305 			un->un_pos.pmode = invalid;
9306 
9307 			mutex_exit(ST_MUTEX);
9308 
9309 			result = scsi_reset(ROUTE, RESET_TARGET);
9310 			/*
9311 			 * if target reset fails, then pull the chain
9312 			 */
9313 			if (result == 0) {
9314 				result = scsi_reset(ROUTE, RESET_ALL);
9315 			}
9316 			mutex_enter(ST_MUTEX);
9317 
9318 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9319 				/* no hope left to recover */
9320 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9321 				    "recovery by resets failed\n");
9322 				return (rval);
9323 			}
9324 		}
9325 	}
9326 
9327 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
9328 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
9329 		if ((un->un_rsvd_status & ST_RESERVE)) {
9330 			un->un_rsvd_status |= ST_LOST_RESERVE;
9331 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9332 			    "Lost Reservation\n");
9333 		}
9334 	}
9335 
9336 	if ((int)un->un_retry_ct++ < st_retry_count) {
9337 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9338 			rval = QUE_COMMAND;
9339 		} else if (bp == un->un_sbufp) {
9340 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
9341 			case SCMD_MODE_SENSE:
9342 			case SCMD_MODE_SELECT:
9343 			case SCMD_READ_BLKLIM:
9344 			case SCMD_REWIND:
9345 			case SCMD_LOAD:
9346 			case SCMD_TEST_UNIT_READY:
9347 				/*
9348 				 * These commands can be rerun with impunity
9349 				 */
9350 				rval = QUE_COMMAND;
9351 				break;
9352 
9353 			default:
9354 				break;
9355 			}
9356 		}
9357 	} else {
9358 		rval = COMMAND_DONE_ERROR;
9359 	}
9360 
9361 	if (un->un_state >= ST_STATE_OPEN) {
9362 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9363 		    fail, scsi_rname(pkt->pkt_reason),
9364 		    (rval == COMMAND_DONE_ERROR)?
9365 		    "giving up" : "retrying command");
9366 	}
9367 	return (rval);
9368 }
9369 
9370 /*
9371  * if the device is busy, then put this bp back on the waitq, on the
9372  * interrupt thread, where we want the head of the queue and not the
9373  * end
9374  *
9375  * The callers of this routine should take measures to save the
9376  * un_throttle in un_last_throttle which will be restored in
9377  * st_intr_restart(). The only exception should be st_intr_restart()
9378  * calling this routine for which the saving is already done.
9379  */
9380 static int
9381 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9382 	clock_t timeout_interval)
9383 {
9384 	struct buf *last_quef;
9385 	int rval = 0;
9386 
9387 	mutex_enter(ST_MUTEX);
9388 
9389 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
9390 
9391 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9392 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9393 
9394 	/*
9395 	 * Check to see if we hit the retry timeout. We check to make sure
9396 	 * this is the first one on the runq and make sure we have not
9397 	 * queued up any more, so this one has to be the last on the list
9398 	 * also. If it is not, we have to fail.  If it is not the first, but
9399 	 * is the last we are in trouble anyway, as we are in the interrupt
9400 	 * context here.
9401 	 */
9402 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9403 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9404 		rval = -1;
9405 		goto exit;
9406 	}
9407 
9408 	/* put the bp back on the waitq */
9409 	if (un->un_quef) {
9410 		last_quef = un->un_quef;
9411 		un->un_quef = bp;
9412 		bp->b_actf = last_quef;
9413 	} else  {
9414 		bp->b_actf = NULL;
9415 		un->un_quef = bp;
9416 		un->un_quel = bp;
9417 	}
9418 
9419 	/*
9420 	 * We know that this is the first and last on the runq at this time,
9421 	 * so we just nullify those two queues
9422 	 */
9423 	un->un_runqf = NULL;
9424 	un->un_runql = NULL;
9425 
9426 	/*
9427 	 * We don't want any other commands being started in the mean time.
9428 	 * If start had just released mutex after putting something on the
9429 	 * runq, we won't even get here.
9430 	 */
9431 	un->un_throttle = 0;
9432 
9433 	/*
9434 	 * send a marker pkt, if appropriate
9435 	 */
9436 	st_hba_unflush(un);
9437 
9438 	/*
9439 	 * all queues are aligned, we are just waiting to
9440 	 * transport
9441 	 */
9442 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9443 
9444 exit:
9445 	mutex_exit(ST_MUTEX);
9446 	return (rval);
9447 }
9448 
9449 /*
9450  * To get one error entry from error stack
9451  */
9452 static int
9453 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
9454 {
9455 #ifdef _MULTI_DATAMODEL
9456 	/*
9457 	 * For use when a 32 bit app makes a call into a
9458 	 * 64 bit ioctl
9459 	 */
9460 	struct mterror_entry32 err_entry32;
9461 #endif /* _MULTI_DATAMODEL */
9462 
9463 	int rval = 0;
9464 	struct mterror_entry err_entry;
9465 	struct mterror_entry_stack *err_link_entry_p;
9466 	size_t arq_status_len_in, arq_status_len_kr;
9467 
9468 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
9469 
9470 	ASSERT(mutex_owned(ST_MUTEX));
9471 
9472 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9473 	    "st_get_error_entry()\n");
9474 
9475 	/*
9476 	 * if error record stack empty, return ENXIO
9477 	 */
9478 	if (un->un_error_entry_stk == NULL) {
9479 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9480 		    "st_get_error_entry: Error Entry Stack Empty!\n");
9481 		rval = ENXIO;
9482 		goto ret;
9483 	}
9484 
9485 	/*
9486 	 * get the top entry from stack
9487 	 */
9488 	err_link_entry_p = un->un_error_entry_stk;
9489 	arq_status_len_kr =
9490 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
9491 
9492 #ifdef _MULTI_DATAMODEL
9493 	switch (ddi_model_convert_from(flag & FMODELS)) {
9494 	case DDI_MODEL_ILP32:
9495 		if (ddi_copyin((void *)arg, &err_entry32,
9496 		    MTERROR_ENTRY_SIZE_32, flag)) {
9497 			rval = EFAULT;
9498 			goto ret;
9499 		}
9500 
9501 		arq_status_len_in =
9502 		    (size_t)err_entry32.mtee_arq_status_len;
9503 
9504 		err_entry32.mtee_cdb_len =
9505 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
9506 
9507 		if (arq_status_len_in > arq_status_len_kr)
9508 			err_entry32.mtee_arq_status_len =
9509 			    (size32_t)arq_status_len_kr;
9510 
9511 		if (ddi_copyout(
9512 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9513 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
9514 		    err_entry32.mtee_cdb_len, flag)) {
9515 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9516 			    "st_get_error_entry: Copy cdb buffer error!");
9517 			rval = EFAULT;
9518 		}
9519 
9520 		if (ddi_copyout(
9521 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9522 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
9523 		    err_entry32.mtee_arq_status_len, flag)) {
9524 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9525 			    "st_get_error_entry: copy arq status error!");
9526 			rval = EFAULT;
9527 		}
9528 
9529 		if (ddi_copyout(&err_entry32, (void *)arg,
9530 		    MTERROR_ENTRY_SIZE_32, flag)) {
9531 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9532 			    "st_get_error_entry: copy arq status out error!");
9533 			rval = EFAULT;
9534 		}
9535 		break;
9536 
9537 	case DDI_MODEL_NONE:
9538 		if (ddi_copyin((void *)arg, &err_entry,
9539 		    MTERROR_ENTRY_SIZE_64, flag)) {
9540 			rval = EFAULT;
9541 			goto ret;
9542 		}
9543 		arq_status_len_in = err_entry.mtee_arq_status_len;
9544 
9545 		err_entry.mtee_cdb_len =
9546 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
9547 
9548 		if (arq_status_len_in > arq_status_len_kr)
9549 			err_entry.mtee_arq_status_len =
9550 			    arq_status_len_kr;
9551 
9552 		if (ddi_copyout(
9553 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9554 		    err_entry.mtee_cdb_buf,
9555 		    err_entry.mtee_cdb_len, flag)) {
9556 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9557 			    "st_get_error_entry: Copy cdb buffer error!");
9558 			rval = EFAULT;
9559 		}
9560 
9561 		if (ddi_copyout(
9562 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9563 		    err_entry.mtee_arq_status,
9564 		    err_entry.mtee_arq_status_len, flag)) {
9565 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9566 			    "st_get_error_entry: copy arq status error!");
9567 			rval = EFAULT;
9568 		}
9569 
9570 		if (ddi_copyout(&err_entry, (void *)arg,
9571 		    MTERROR_ENTRY_SIZE_64, flag)) {
9572 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9573 			    "st_get_error_entry: copy arq status out error!");
9574 			rval = EFAULT;
9575 		}
9576 		break;
9577 	}
9578 #else /* _MULTI_DATAMODEL */
9579 	if (ddi_copyin((void *)arg, &err_entry,
9580 	    MTERROR_ENTRY_SIZE_64, flag)) {
9581 		rval = EFAULT;
9582 		goto ret;
9583 	}
9584 	arq_status_len_in = err_entry.mtee_arq_status_len;
9585 
9586 	err_entry.mtee_cdb_len =
9587 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
9588 
9589 	if (arq_status_len_in > arq_status_len_kr)
9590 		err_entry.mtee_arq_status_len =
9591 		    arq_status_len_kr;
9592 
9593 	if (ddi_copyout(
9594 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9595 	    err_entry.mtee_cdb_buf,
9596 	    err_entry.mtee_cdb_len, flag)) {
9597 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9598 		    "st_get_error_entry: Copy cdb buffer error!");
9599 		rval = EFAULT;
9600 	}
9601 
9602 	if (ddi_copyout(
9603 	    err_link_entry_p->mtees_entry.mtee_arq_status,
9604 	    err_entry.mtee_arq_status,
9605 	    err_entry.mtee_arq_status_len, flag)) {
9606 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9607 		    "st_get_error_entry: copy arq status buffer error!");
9608 		rval = EFAULT;
9609 	}
9610 
9611 	if (ddi_copyout(&err_entry, (void *)arg,
9612 	    MTERROR_ENTRY_SIZE_64, flag)) {
9613 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9614 		    "st_get_error_entry: copy arq status out error!");
9615 		rval = EFAULT;
9616 	}
9617 #endif /* _MULTI_DATAMODEL */
9618 
9619 	/*
9620 	 * update stack
9621 	 */
9622 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
9623 
9624 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
9625 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
9626 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
9627 
9628 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
9629 	    SECMDS_STATUS_SIZE);
9630 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
9631 
9632 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
9633 	err_link_entry_p = NULL;
9634 ret:
9635 	return (rval);
9636 }
9637 
9638 /*
9639  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
9640  * the scsi CDB command which causes the error and generates sense data and
9641  * the scsi status.
9642  *
9643  *      error-record stack
9644  *
9645  *
9646  *             TOP                                     BOTTOM
9647  *              ------------------------------------------
9648  *              |   0   |   1   |   2   |   ...  |   n   |
9649  *              ------------------------------------------
9650  *                  ^
9651  *                  |
9652  *       pointer to error entry
9653  *
9654  * when st driver generates one sense data record, it creates a error-entry
9655  * and pushes it onto the stack.
9656  *
9657  */
9658 
9659 static void
9660 st_update_error_stack(struct scsi_tape *un,
9661 			struct scsi_pkt *pkt,
9662 			struct scsi_arq_status *cmd)
9663 {
9664 	struct mterror_entry_stack *err_entry_tmp;
9665 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
9666 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
9667 
9668 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
9669 
9670 	ASSERT(mutex_owned(ST_MUTEX));
9671 
9672 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9673 	    "st_update_error_stack()\n");
9674 
9675 	ASSERT(cmd);
9676 	ASSERT(cdbp);
9677 	if (cdblen == 0) {
9678 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9679 		    "st_update_error_stack: CDB length error!\n");
9680 		return;
9681 	}
9682 
9683 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
9684 	ASSERT(err_entry_tmp != NULL);
9685 
9686 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
9687 	    kmem_alloc(cdblen, KM_SLEEP);
9688 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
9689 
9690 	err_entry_tmp->mtees_entry.mtee_arq_status =
9691 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
9692 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
9693 
9694 	/*
9695 	 * copy cdb command & length to current error entry
9696 	 */
9697 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
9698 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
9699 
9700 	/*
9701 	 * copy scsi status length to current error entry
9702 	 */
9703 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
9704 	    SECMDS_STATUS_SIZE;
9705 
9706 	/*
9707 	 * copy sense data and scsi status to current error entry
9708 	 */
9709 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
9710 	    SECMDS_STATUS_SIZE);
9711 
9712 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
9713 	un->un_error_entry_stk = err_entry_tmp;
9714 
9715 }
9716 
9717 /*
9718  * Empty all the error entry in stack
9719  */
9720 static void
9721 st_empty_error_stack(struct scsi_tape *un)
9722 {
9723 	struct mterror_entry_stack *linkp;
9724 
9725 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
9726 
9727 	ASSERT(mutex_owned(ST_MUTEX));
9728 
9729 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9730 	    "st_empty_entry_stack()\n");
9731 
9732 	while (un->un_error_entry_stk != NULL) {
9733 		linkp = un->un_error_entry_stk;
9734 		un->un_error_entry_stk =
9735 		    un->un_error_entry_stk->mtees_nextp;
9736 
9737 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
9738 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
9739 			    linkp->mtees_entry.mtee_cdb_len);
9740 
9741 		if (linkp->mtees_entry.mtee_arq_status != NULL)
9742 			kmem_free(linkp->mtees_entry.mtee_arq_status,
9743 			    linkp->mtees_entry.mtee_arq_status_len);
9744 
9745 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
9746 		linkp = NULL;
9747 	}
9748 }
9749 
9750 static int
9751 st_handle_sense(struct scsi_tape *un, struct buf *bp)
9752 {
9753 	struct scsi_pkt *pkt = BP_PKT(bp);
9754 	struct scsi_pkt *rqpkt = un->un_rqs;
9755 	struct scsi_arq_status arqstat;
9756 
9757 	int rval = COMMAND_DONE_ERROR;
9758 	int amt;
9759 
9760 	ST_FUNC(ST_DEVINFO, st_handle_sense);
9761 
9762 	ASSERT(mutex_owned(ST_MUTEX));
9763 
9764 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9765 	    "st_handle_sense()\n");
9766 
9767 	if (SCBP(rqpkt)->sts_busy) {
9768 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9769 		    "busy unit on request sense\n");
9770 		if ((int)un->un_retry_ct++ < st_retry_count) {
9771 			rval = QUE_BUSY_COMMAND;
9772 		}
9773 		return (rval);
9774 	} else if (SCBP(rqpkt)->sts_chk) {
9775 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9776 		    "Check Condition on REQUEST SENSE\n");
9777 		return (rval);
9778 	}
9779 
9780 	/* was there enough data? */
9781 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
9782 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
9783 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9784 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9785 		    "REQUEST SENSE couldn't get sense data\n");
9786 		return (rval);
9787 	}
9788 
9789 	bcopy(SCBP(pkt), &arqstat.sts_status,
9790 	    sizeof (struct scsi_status));
9791 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
9792 	    sizeof (struct scsi_status));
9793 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
9794 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
9795 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
9796 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
9797 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
9798 
9799 	/*
9800 	 * copy one arqstat entry in the sense data buffer
9801 	 */
9802 	st_update_error_stack(un, pkt, &arqstat);
9803 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
9804 }
9805 
9806 static int
9807 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
9808 {
9809 	struct scsi_pkt *pkt = BP_PKT(bp);
9810 	struct scsi_arq_status *arqstat =
9811 	    (struct scsi_arq_status *)pkt->pkt_scbp;
9812 	int rval = COMMAND_DONE_ERROR;
9813 	int amt;
9814 
9815 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
9816 
9817 	ASSERT(mutex_owned(ST_MUTEX));
9818 
9819 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9820 	    "st_handle_autosense()\n");
9821 
9822 	if (arqstat->sts_rqpkt_status.sts_busy) {
9823 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9824 		    "busy unit on request sense\n");
9825 		/*
9826 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
9827 		 * the disadvantage is that we do not have any delay for the
9828 		 * second retry of rqsense and we have to keep a packet around
9829 		 */
9830 		return (QUE_SENSE);
9831 
9832 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
9833 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9834 		    "transport error on REQUEST SENSE\n");
9835 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
9836 		    ((arqstat->sts_rqpkt_statistics &
9837 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
9838 			mutex_exit(ST_MUTEX);
9839 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9840 				/*
9841 				 * if target reset fails, then pull the chain
9842 				 */
9843 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
9844 					ST_DEBUG6(ST_DEVINFO, st_label,
9845 					    CE_WARN,
9846 					    "recovery by resets failed\n");
9847 				}
9848 			}
9849 			mutex_enter(ST_MUTEX);
9850 		}
9851 		return (rval);
9852 
9853 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
9854 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9855 		    "Check Condition on REQUEST SENSE\n");
9856 		return (rval);
9857 	}
9858 
9859 
9860 	/* was there enough data? */
9861 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9862 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
9863 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9864 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9865 		    "REQUEST SENSE couldn't get sense data\n");
9866 		return (rval);
9867 	}
9868 
9869 	/*
9870 	 * copy one arqstat entry in the sense data buffer
9871 	 */
9872 	st_update_error_stack(un, pkt, arqstat);
9873 
9874 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
9875 
9876 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
9877 }
9878 
9879 static int
9880 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
9881 	struct scsi_status *statusp)
9882 {
9883 	struct scsi_pkt *pkt = BP_PKT(bp);
9884 	int rval = COMMAND_DONE_ERROR;
9885 	long resid;
9886 	struct scsi_extended_sense *sensep = ST_RQSENSE;
9887 	int severity;
9888 	int get_error;
9889 
9890 	ST_FUNC(ST_DEVINFO, st_decode_sense);
9891 
9892 	ASSERT(mutex_owned(ST_MUTEX));
9893 
9894 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9895 	    "st_decode_sense()\n");
9896 
9897 	/*
9898 	 * For uscsi commands, squirrel away a copy of the
9899 	 * results of the Request Sense.
9900 	 */
9901 	if (USCSI_CMD(bp)) {
9902 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9903 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
9904 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
9905 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
9906 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
9907 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
9908 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9909 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
9910 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
9911 		}
9912 	}
9913 
9914 	/*
9915 	 * If the drive is an MT-02, reposition the
9916 	 * secondary error code into the proper place.
9917 	 *
9918 	 * XXX	MT-02 is non-CCS tape, so secondary error code
9919 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
9920 	 * so it's in byte 12.
9921 	 */
9922 	if (un->un_dp->type == ST_TYPE_EMULEX) {
9923 		sensep->es_code = sensep->es_add_info[0];
9924 	}
9925 
9926 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
9927 	    (caddr_t)&CDBP(pkt)->scc_cmd);
9928 
9929 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
9930 	    sizeof (*sensep));
9931 
9932 	/* for normal I/O check extract the resid values. */
9933 	if (bp != un->un_sbufp) {
9934 		if (sensep->es_valid) {
9935 			resid =
9936 			    (sensep->es_info_1 << 24) |
9937 			    (sensep->es_info_2 << 16) |
9938 			    (sensep->es_info_3 << 8)  |
9939 			    (sensep->es_info_4);
9940 			/* If fixed block */
9941 			if (un->un_bsize) {
9942 				resid *= un->un_bsize;
9943 			}
9944 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
9945 			resid = pkt->pkt_resid;
9946 		} else {
9947 			resid = bp->b_bcount;
9948 		}
9949 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9950 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
9951 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
9952 		    resid,
9953 		    (sensep->es_info_1 << 24) |
9954 		    (sensep->es_info_2 << 16) |
9955 		    (sensep->es_info_3 << 8)  |
9956 		    (sensep->es_info_4),
9957 		    pkt->pkt_resid);
9958 		/*
9959 		 * The problem is, what should we believe?
9960 		 */
9961 		if (resid && (pkt->pkt_resid == 0)) {
9962 			pkt->pkt_resid = resid;
9963 		}
9964 	} else {
9965 		/*
9966 		 * If the command is SCMD_SPACE, we need to get the
9967 		 * residual as returned in the sense data, to adjust
9968 		 * our idea of current tape position correctly
9969 		 */
9970 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9971 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9972 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
9973 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9974 		    (sensep->es_valid)) {
9975 			resid =
9976 			    (sensep->es_info_1 << 24) |
9977 			    (sensep->es_info_2 << 16) |
9978 			    (sensep->es_info_3 << 8)  |
9979 			    (sensep->es_info_4);
9980 			bp->b_resid = resid;
9981 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9982 			    "st_handle_sense(other):	resid=%ld\n", resid);
9983 		} else {
9984 			/*
9985 			 * If the special command is SCMD_READ,
9986 			 * the correct resid will be set later.
9987 			 */
9988 			resid = bp->b_bcount;
9989 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9990 			    "st_handle_sense(special read):  resid=%ld\n",
9991 			    resid);
9992 		}
9993 	}
9994 
9995 	if ((un->un_state >= ST_STATE_OPEN) &&
9996 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9997 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
9998 		    "Failed CDB", (char *)pkt->pkt_cdbp);
9999 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10000 		    "sense data", (char *)sensep, amt);
10001 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10002 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10003 		    bp->b_bcount, resid, pkt->pkt_resid);
10004 	}
10005 
10006 	switch (un->un_status = sensep->es_key) {
10007 	case KEY_NO_SENSE:
10008 		severity = SCSI_ERR_INFO;
10009 
10010 		/*
10011 		 * Erase, locate or rewind operation in progress, retry
10012 		 * ASC  ASCQ
10013 		 *  00   18    Erase operation in progress
10014 		 *  00   19    Locate operation in progress
10015 		 *  00   1A    Rewind operation in progress
10016 		 */
10017 		if (sensep->es_add_code == 0 &&
10018 		    ((sensep->es_qual_code == 0x18) ||
10019 		    (sensep->es_qual_code == 0x19) ||
10020 		    (sensep->es_qual_code == 0x1a))) {
10021 			rval = QUE_COMMAND;
10022 			break;
10023 		}
10024 
10025 		goto common;
10026 
10027 	case KEY_RECOVERABLE_ERROR:
10028 		severity = SCSI_ERR_RECOVERED;
10029 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10030 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10031 			if (un->un_dp->options &
10032 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10033 				rval = QUE_LAST_COMMAND;
10034 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10035 				    severity, un->un_pos.lgclblkno,
10036 				    un->un_err_pos.lgclblkno, scsi_cmds,
10037 				    sensep);
10038 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10039 				    "Command will be retried\n");
10040 			} else {
10041 				severity = SCSI_ERR_FATAL;
10042 				rval = COMMAND_DONE_ERROR_RECOVERED;
10043 				ST_DO_ERRSTATS(un, st_softerrs);
10044 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10045 				    severity, un->un_pos.lgclblkno,
10046 				    un->un_err_pos.lgclblkno, scsi_cmds,
10047 				    sensep);
10048 			}
10049 			break;
10050 		}
10051 common:
10052 		/*
10053 		 * XXX only want reads to be stopped by filemarks.
10054 		 * Don't want them to be stopped by EOT.  EOT matters
10055 		 * only on write.
10056 		 */
10057 		if (sensep->es_filmk && !sensep->es_eom) {
10058 			rval = COMMAND_DONE;
10059 		} else if (sensep->es_eom) {
10060 			rval = COMMAND_DONE;
10061 		} else if (sensep->es_ili) {
10062 			/*
10063 			 * Fun with variable length record devices:
10064 			 * for specifying larger blocks sizes than the
10065 			 * actual physical record size.
10066 			 */
10067 			if (un->un_bsize == 0 && resid > 0) {
10068 				/*
10069 				 * XXX! Ugly.
10070 				 * The requested blocksize is > tape blocksize,
10071 				 * so this is ok, so we just return the
10072 				 * actual size xferred.
10073 				 */
10074 				pkt->pkt_resid = resid;
10075 				rval = COMMAND_DONE;
10076 			} else if (un->un_bsize == 0 && resid < 0) {
10077 				/*
10078 				 * The requested blocksize is < tape blocksize,
10079 				 * so this is not ok, so we err with ENOMEM
10080 				 */
10081 				rval = COMMAND_DONE_ERROR_RECOVERED;
10082 				st_bioerror(bp, ENOMEM);
10083 			} else {
10084 				ST_DO_ERRSTATS(un, st_softerrs);
10085 				severity = SCSI_ERR_FATAL;
10086 				rval = COMMAND_DONE_ERROR;
10087 				st_bioerror(bp, EINVAL);
10088 			}
10089 		} else {
10090 			/*
10091 			 * we hope and pray for this just being
10092 			 * something we can ignore (ie. a
10093 			 * truly recoverable soft error)
10094 			 */
10095 			rval = COMMAND_DONE;
10096 		}
10097 		if (sensep->es_filmk) {
10098 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10099 			    "filemark\n");
10100 			un->un_status = SUN_KEY_EOF;
10101 			un->un_pos.eof = ST_EOF_PENDING;
10102 			SET_PE_FLAG(un);
10103 		}
10104 
10105 		/*
10106 		 * ignore eom when reading, a fmk should terminate reading
10107 		 */
10108 		if ((sensep->es_eom) &&
10109 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10110 			if ((sensep->es_add_code == 0) &&
10111 			    (sensep->es_qual_code == 4)) {
10112 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10113 				    "bot\n");
10114 				un->un_status = SUN_KEY_BOT;
10115 				un->un_pos.eof = ST_NO_EOF;
10116 				un->un_pos.lgclblkno = 0;
10117 				un->un_pos.fileno = 0;
10118 				un->un_pos.blkno = 0;
10119 				un->un_pos.pmode = legacy;
10120 			} else {
10121 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10122 				    "eom\n");
10123 				un->un_status = SUN_KEY_EOT;
10124 				un->un_pos.eof = ST_EOM;
10125 			}
10126 			SET_PE_FLAG(un);
10127 		}
10128 
10129 		break;
10130 
10131 	case KEY_ILLEGAL_REQUEST:
10132 
10133 		if (un->un_laststate >= ST_STATE_OPEN) {
10134 			ST_DO_ERRSTATS(un, st_softerrs);
10135 			severity = SCSI_ERR_FATAL;
10136 		} else {
10137 			severity = SCSI_ERR_INFO;
10138 		}
10139 		break;
10140 
10141 	case KEY_MEDIUM_ERROR:
10142 		ST_DO_ERRSTATS(un, st_harderrs);
10143 		severity = SCSI_ERR_FATAL;
10144 
10145 		/*
10146 		 * for (buffered) writes, a medium error must be fatal
10147 		 */
10148 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
10149 			rval = COMMAND_DONE_ERROR_RECOVERED;
10150 		}
10151 
10152 check_keys:
10153 		/*
10154 		 * attempt to process the keys in the presence of
10155 		 * other errors
10156 		 */
10157 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10158 			/*
10159 			 * Fun with variable length record devices:
10160 			 * for specifying larger blocks sizes than the
10161 			 * actual physical record size.
10162 			 */
10163 			if (un->un_bsize == 0 && resid > 0) {
10164 				/*
10165 				 * XXX! Ugly
10166 				 */
10167 				pkt->pkt_resid = resid;
10168 			} else if (un->un_bsize == 0 && resid < 0) {
10169 				st_bioerror(bp, EINVAL);
10170 			} else {
10171 				severity = SCSI_ERR_FATAL;
10172 				rval = COMMAND_DONE_ERROR;
10173 				st_bioerror(bp, EINVAL);
10174 			}
10175 		}
10176 		if (sensep->es_filmk) {
10177 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10178 			    "filemark\n");
10179 			un->un_status = SUN_KEY_EOF;
10180 			un->un_pos.eof = ST_EOF_PENDING;
10181 			SET_PE_FLAG(un);
10182 		}
10183 
10184 		/*
10185 		 * ignore eom when reading, a fmk should terminate reading
10186 		 */
10187 		if ((sensep->es_eom) &&
10188 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10189 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10190 			un->un_status = SUN_KEY_EOT;
10191 			un->un_pos.eof = ST_EOM;
10192 			SET_PE_FLAG(un);
10193 		}
10194 
10195 		break;
10196 
10197 	case KEY_VOLUME_OVERFLOW:
10198 		ST_DO_ERRSTATS(un, st_softerrs);
10199 		un->un_pos.eof = ST_EOM;
10200 		severity = SCSI_ERR_FATAL;
10201 		rval = COMMAND_DONE_ERROR;
10202 		goto check_keys;
10203 
10204 	case KEY_HARDWARE_ERROR:
10205 		ST_DO_ERRSTATS(un, st_harderrs);
10206 		severity = SCSI_ERR_FATAL;
10207 		rval = COMMAND_DONE_ERROR;
10208 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10209 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10210 		break;
10211 
10212 	case KEY_BLANK_CHECK:
10213 		ST_DO_ERRSTATS(un, st_softerrs);
10214 		severity = SCSI_ERR_INFO;
10215 
10216 		/*
10217 		 * if not a special request and some data was xferred then it
10218 		 * it is not an error yet
10219 		 */
10220 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10221 			/*
10222 			 * no error for read with or without data xferred
10223 			 */
10224 			un->un_status = SUN_KEY_EOT;
10225 			un->un_pos.eof = ST_EOT;
10226 			rval = COMMAND_DONE_ERROR;
10227 			SET_PE_FLAG(un);
10228 			goto check_keys;
10229 		} else if (bp != un->un_sbufp &&
10230 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10231 			rval = COMMAND_DONE;
10232 		} else {
10233 			rval = COMMAND_DONE_ERROR_RECOVERED;
10234 		}
10235 
10236 		if (un->un_laststate >= ST_STATE_OPEN) {
10237 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10238 			    "blank check\n");
10239 			un->un_pos.eof = ST_EOM;
10240 		}
10241 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10242 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10243 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10244 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10245 			/*
10246 			 * we were doing a fast forward by skipping
10247 			 * multiple fmk at the time
10248 			 */
10249 			st_bioerror(bp, EIO);
10250 			severity = SCSI_ERR_RECOVERED;
10251 			rval	 = COMMAND_DONE;
10252 		}
10253 		SET_PE_FLAG(un);
10254 		goto check_keys;
10255 
10256 	case KEY_WRITE_PROTECT:
10257 		if (st_wrongtapetype(un)) {
10258 			un->un_status = SUN_KEY_WRONGMEDIA;
10259 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10260 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
10261 			severity = SCSI_ERR_UNKNOWN;
10262 		} else {
10263 			severity = SCSI_ERR_FATAL;
10264 		}
10265 		ST_DO_ERRSTATS(un, st_harderrs);
10266 		rval = COMMAND_DONE_ERROR;
10267 		st_bioerror(bp, EACCES);
10268 		break;
10269 
10270 	case KEY_UNIT_ATTENTION:
10271 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10272 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10273 
10274 		/*
10275 		 * If we have detected a Bus Reset and the tape
10276 		 * drive has been reserved.
10277 		 */
10278 		if (ST_RQSENSE->es_add_code == 0x29 &&
10279 		    (un->un_rsvd_status & ST_RESERVE)) {
10280 			un->un_rsvd_status |= ST_LOST_RESERVE;
10281 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10282 			    "st_decode_sense: Lost Reservation\n");
10283 		}
10284 
10285 		if (un->un_state <= ST_STATE_OPENING) {
10286 			/*
10287 			 * Look, the tape isn't open yet, now determine
10288 			 * if the cause is a BUS RESET, Save the file and
10289 			 * Block positions for the callers to recover from
10290 			 * the loss of position.
10291 			 */
10292 			if (un->un_pos.pmode != invalid) {
10293 				if (ST_RQSENSE->es_add_code == 0x29) {
10294 					un->un_save_fileno = un->un_pos.fileno;
10295 					un->un_save_blkno = un->un_pos.blkno;
10296 					un->un_restore_pos = 1;
10297 				}
10298 			}
10299 
10300 			if ((int)un->un_retry_ct++ < st_retry_count) {
10301 				rval = QUE_COMMAND;
10302 			} else {
10303 				rval = COMMAND_DONE_ERROR;
10304 			}
10305 			severity = SCSI_ERR_INFO;
10306 
10307 		} else {
10308 			/*
10309 			 * Check if it is an Unexpected Unit Attention.
10310 			 * If state is >= ST_STATE_OPEN, we have
10311 			 * already done the initialization .
10312 			 * In this case it is Fatal Error
10313 			 * since no further reading/writing
10314 			 * can be done with fileno set to < 0.
10315 			 */
10316 			if (un->un_state >= ST_STATE_OPEN) {
10317 				ST_DO_ERRSTATS(un, st_harderrs);
10318 				severity = SCSI_ERR_FATAL;
10319 			} else {
10320 				severity = SCSI_ERR_INFO;
10321 			}
10322 			rval = COMMAND_DONE_ERROR;
10323 		}
10324 		un->un_pos.pmode = invalid;
10325 
10326 		break;
10327 
10328 	case KEY_NOT_READY:
10329 		/*
10330 		 * If in process of getting ready retry.
10331 		 */
10332 		if (sensep->es_add_code  == 0x04 &&
10333 		    sensep->es_qual_code == 0x01 &&
10334 		    un->un_retry_ct++ < st_retry_count) {
10335 			rval = QUE_COMMAND;
10336 			severity = SCSI_ERR_INFO;
10337 		} else {
10338 			/* give up */
10339 			rval = COMMAND_DONE_ERROR;
10340 			severity = SCSI_ERR_FATAL;
10341 		}
10342 
10343 		/*
10344 		 * If this was an error and after device opened
10345 		 * do error stats.
10346 		 */
10347 		if (rval == COMMAND_DONE_ERROR &&
10348 		    un->un_state > ST_STATE_OPENING) {
10349 			ST_DO_ERRSTATS(un, st_harderrs);
10350 		}
10351 
10352 		if (ST_RQSENSE->es_add_code == 0x3a) {
10353 			if (st_error_level >= SCSI_ERR_FATAL)
10354 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10355 				    "Tape not inserted in drive\n");
10356 			un->un_mediastate = MTIO_EJECTED;
10357 			cv_broadcast(&un->un_state_cv);
10358 		}
10359 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
10360 		    (rval != QUE_COMMAND))
10361 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10362 		break;
10363 
10364 	case KEY_ABORTED_COMMAND:
10365 
10366 		/*
10367 		 * Probably a parity error...
10368 		 * if we retry here then this may cause data to be
10369 		 * written twice or data skipped during reading
10370 		 */
10371 		ST_DO_ERRSTATS(un, st_harderrs);
10372 		severity = SCSI_ERR_FATAL;
10373 		rval = COMMAND_DONE_ERROR;
10374 		goto check_keys;
10375 
10376 	default:
10377 		/*
10378 		 * Undecoded sense key.	 Try retries and hope
10379 		 * that will fix the problem.  Otherwise, we're
10380 		 * dead.
10381 		 */
10382 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10383 		    "Unhandled Sense Key '%s'\n",
10384 		    sense_keys[un->un_status]);
10385 		ST_DO_ERRSTATS(un, st_harderrs);
10386 		severity = SCSI_ERR_FATAL;
10387 		rval = COMMAND_DONE_ERROR;
10388 		goto check_keys;
10389 	}
10390 
10391 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
10392 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
10393 	    (un->un_laststate > ST_STATE_OPENING) &&
10394 	    (severity >= st_error_level))) {
10395 
10396 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
10397 		    un->un_pos.lgclblkno, un->un_err_pos.lgclblkno,
10398 		    scsi_cmds, sensep);
10399 		if (sensep->es_filmk) {
10400 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10401 			    "File Mark Detected\n");
10402 		}
10403 		if (sensep->es_eom) {
10404 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10405 			    "End-of-Media Detected\n");
10406 		}
10407 		if (sensep->es_ili) {
10408 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10409 			    "Incorrect Length Indicator Set\n");
10410 		}
10411 	}
10412 	get_error = geterror(bp);
10413 	if (((rval == COMMAND_DONE_ERROR) ||
10414 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
10415 	    ((get_error == EIO) || (get_error == 0))) {
10416 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
10417 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
10418 		if (un->un_rqs_state & ST_RQS_READ) {
10419 			un->un_rqs_state &= ~(ST_RQS_READ);
10420 		} else {
10421 			un->un_rqs_state |= ST_RQS_OVR;
10422 		}
10423 	}
10424 
10425 	return (rval);
10426 }
10427 
10428 
10429 static int
10430 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
10431 {
10432 	int status = TRAN_ACCEPT;
10433 
10434 	mutex_enter(ST_MUTEX);
10435 
10436 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
10437 
10438 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10439 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
10440 
10441 	/*
10442 	 * Check to see if we hit the retry timeout. We check to make sure
10443 	 * this is the first one on the runq and make sure we have not
10444 	 * queued up any more, so this one has to be the last on the list
10445 	 * also. If it is not, we have to fail.  If it is not the first, but
10446 	 * is the last we are in trouble anyway, as we are in the interrupt
10447 	 * context here.
10448 	 */
10449 	if (((int)un->un_retry_ct > st_retry_count) ||
10450 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
10451 		goto exit;
10452 	}
10453 
10454 	if (un->un_throttle) {
10455 		un->un_last_throttle = un->un_throttle;
10456 		un->un_throttle = 0;
10457 	}
10458 
10459 	/*
10460 	 * Here we know : bp is the first and last one on the runq
10461 	 * it is not necessary to put it back on the head of the
10462 	 * waitq and then move from waitq to runq. Save this queuing
10463 	 * and call scsi_transport.
10464 	 */
10465 
10466 	mutex_exit(ST_MUTEX);
10467 
10468 	status = scsi_transport(BP_PKT(bp));
10469 
10470 	mutex_enter(ST_MUTEX);
10471 
10472 	if (status == TRAN_ACCEPT) {
10473 		un->un_tran_retry_ct = 0;
10474 		if (un->un_last_throttle) {
10475 			un->un_throttle = un->un_last_throttle;
10476 		}
10477 		mutex_exit(ST_MUTEX);
10478 
10479 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10480 		    "restart transport \n");
10481 		return (0);
10482 	}
10483 
10484 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
10485 	mutex_exit(ST_MUTEX);
10486 
10487 	if (status == TRAN_BUSY) {
10488 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
10489 			return (0);
10490 		}
10491 	}
10492 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10493 	    "restart transport rejected\n");
10494 	mutex_enter(ST_MUTEX);
10495 	ST_DO_ERRSTATS(un, st_transerrs);
10496 	if (un->un_last_throttle) {
10497 		un->un_throttle = un->un_last_throttle;
10498 	}
10499 exit:
10500 	mutex_exit(ST_MUTEX);
10501 	return (-1);
10502 }
10503 
10504 static int
10505 st_wrongtapetype(struct scsi_tape *un)
10506 {
10507 
10508 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
10509 
10510 	ASSERT(mutex_owned(ST_MUTEX));
10511 
10512 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
10513 
10514 	/*
10515 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
10516 	 */
10517 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
10518 		switch (un->un_dp->type) {
10519 		case ST_TYPE_WANGTEK:
10520 		case ST_TYPE_ARCHIVE:
10521 			/*
10522 			 * If this really worked, we could go off of
10523 			 * the density codes set in the modesense
10524 			 * page. For this drive, 0x10 == QIC-120,
10525 			 * 0xf == QIC-150, and 0x5 should be for
10526 			 * both QIC-24 and, maybe, QIC-11. However,
10527 			 * the h/w doesn't do what the manual says
10528 			 * that it should, so we'll key off of
10529 			 * getting a WRITE PROTECT error AND wp *not*
10530 			 * set in the mode sense information.
10531 			 */
10532 			/*
10533 			 * XXX but we already know that status is
10534 			 * write protect, so don't check it again.
10535 			 */
10536 
10537 			if (un->un_status == KEY_WRITE_PROTECT &&
10538 			    un->un_mspl->wp == 0) {
10539 				return (1);
10540 			}
10541 			break;
10542 		default:
10543 			break;
10544 		}
10545 	}
10546 	return (0);
10547 }
10548 
10549 static int
10550 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
10551 {
10552 	int action;
10553 
10554 	ST_FUNC(ST_DEVINFO, st_check_error);
10555 
10556 	ASSERT(mutex_owned(ST_MUTEX));
10557 
10558 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
10559 
10560 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
10561 		action = COMMAND_DONE_EACCES;
10562 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
10563 	} else if (SCBP(pkt)->sts_busy) {
10564 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
10565 		if ((int)un->un_retry_ct++ < st_retry_count) {
10566 			action = QUE_BUSY_COMMAND;
10567 		} else if ((un->un_rsvd_status &
10568 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10569 			/*
10570 			 * If this is a command done before reserve is done
10571 			 * don't reset.
10572 			 */
10573 			action = COMMAND_DONE_ERROR;
10574 		} else {
10575 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10576 			    "unit busy too long\n");
10577 			mutex_exit(ST_MUTEX);
10578 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
10579 				(void) scsi_reset(ROUTE, RESET_ALL);
10580 			}
10581 			mutex_enter(ST_MUTEX);
10582 			action = COMMAND_DONE_ERROR;
10583 		}
10584 	} else if (SCBP(pkt)->sts_chk) {
10585 		/*
10586 		 * we should only get here if the auto rqsense failed
10587 		 * thru a uscsi cmd without autorequest sense
10588 		 * so we just try again
10589 		 */
10590 		action = QUE_SENSE;
10591 	} else {
10592 		action = COMMAND_DONE;
10593 	}
10594 	return (action);
10595 }
10596 
10597 static void
10598 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
10599 {
10600 	int nblks;
10601 
10602 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
10603 
10604 	ASSERT(mutex_owned(ST_MUTEX));
10605 
10606 	/* If variable block mode */
10607 	if (un->un_bsize == 0) {
10608 		nblks = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
10609 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid) / ONE_K;
10610 	} else {
10611 		nblks = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
10612 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
10613 	}
10614 	un->un_pos.blkno += nblks;
10615 	un->un_pos.lgclblkno += nblks;
10616 }
10617 
10618 static void
10619 st_set_state(struct scsi_tape *un)
10620 {
10621 	struct buf *bp = un->un_runqf;
10622 	struct scsi_pkt *sp = BP_PKT(bp);
10623 	struct uscsi_cmd *ucmd;
10624 
10625 	ST_FUNC(ST_DEVINFO, st_set_state);
10626 
10627 	ASSERT(mutex_owned(ST_MUTEX));
10628 
10629 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10630 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
10631 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
10632 
10633 	if (bp != un->un_sbufp) {
10634 #ifdef STDEBUG
10635 		if (DEBUGGING && sp->pkt_resid) {
10636 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10637 			    "pkt_resid %ld bcount %ld\n",
10638 			    sp->pkt_resid, bp->b_bcount);
10639 		}
10640 #endif
10641 		bp->b_resid = sp->pkt_resid;
10642 		st_calc_bnum(un, bp);
10643 		if (bp->b_flags & B_READ) {
10644 			un->un_lastop = ST_OP_READ;
10645 			un->un_fmneeded = 0;
10646 		} else {
10647 			un->un_lastop = ST_OP_WRITE;
10648 			if (un->un_dp->options & ST_REEL) {
10649 				un->un_fmneeded = 2;
10650 			} else {
10651 				un->un_fmneeded = 1;
10652 			}
10653 		}
10654 		/*
10655 		 * all is honky dory at this point, so let's
10656 		 * readjust the throttle, to increase speed, if we
10657 		 * have not throttled down.
10658 		 */
10659 		if (un->un_throttle) {
10660 			un->un_throttle = un->un_max_throttle;
10661 		}
10662 	} else {
10663 		optype new_lastop;
10664 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
10665 
10666 		un->un_lastop = ST_OP_CTL;
10667 
10668 		switch (cmd) {
10669 		case SCMD_WRITE:
10670 			bp->b_resid = sp->pkt_resid;
10671 			new_lastop = ST_OP_WRITE;
10672 			st_calc_bnum(un, bp);
10673 			if (un->un_dp->options & ST_REEL) {
10674 				un->un_fmneeded = 2;
10675 			} else {
10676 				un->un_fmneeded = 1;
10677 			}
10678 			break;
10679 		case SCMD_READ:
10680 			bp->b_resid = sp->pkt_resid;
10681 			new_lastop = ST_OP_READ;
10682 			st_calc_bnum(un, bp);
10683 			un->un_fmneeded = 0;
10684 			break;
10685 		case SCMD_WRITE_FILE_MARK:
10686 		{
10687 			int fmdone;
10688 
10689 			if (un->un_pos.eof != ST_EOM) {
10690 				un->un_pos.eof = ST_NO_EOF;
10691 			}
10692 			fmdone = (bp->b_bcount - bp->b_resid);
10693 			if (fmdone > 0) {
10694 				un->un_lastop = new_lastop = ST_OP_WEOF;
10695 				un->un_pos.lgclblkno += fmdone;
10696 				un->un_pos.fileno += fmdone;
10697 				un->un_pos.blkno = 0;
10698 			} else {
10699 				new_lastop = ST_OP_CTL;
10700 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
10701 				    "Flushed buffer\n");
10702 			}
10703 			if (fmdone > un->un_fmneeded) {
10704 				un->un_fmneeded = 0;
10705 			} else {
10706 				un->un_fmneeded -= fmdone;
10707 			}
10708 			break;
10709 		}
10710 		case SCMD_REWIND:
10711 			un->un_pos.eof = ST_NO_EOF;
10712 			un->un_pos.fileno = 0;
10713 			un->un_pos.blkno = 0;
10714 			un->un_pos.lgclblkno = 0;
10715 			un->un_pos.pmode = legacy;
10716 			new_lastop = ST_OP_CTL;
10717 			break;
10718 
10719 		case SCMD_SPACE:
10720 		{
10721 			int count;
10722 			long resid;
10723 			int done;
10724 
10725 			count = (int)SPACE_CNT(bp->b_bcount);
10726 			/* if was a uscsi space cmd b_bcount == 0 */
10727 			if (count == 0) {
10728 				count =
10729 				    (sp->pkt_cdbp[2] << 16) |
10730 				    (sp->pkt_cdbp[3] << 8)  |
10731 				    (sp->pkt_cdbp[4]);
10732 			}
10733 			resid = (long)SPACE_CNT(bp->b_resid);
10734 			if (count >= 0) {
10735 				done = (count - resid);
10736 			} else {
10737 				done = ((-count) - resid);
10738 			}
10739 			if (done > 0) {
10740 				un->un_lastop = new_lastop = ST_OP_CTL;
10741 			} else {
10742 				new_lastop = ST_OP_CTL;
10743 			}
10744 
10745 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
10746 			    "space cmd: cdb[1] = %s\n"
10747 			    "space data:       = 0x%lx\n"
10748 			    "space count:      = %d\n"
10749 			    "space resid:      = %ld\n"
10750 			    "spaces done:      = %d\n"
10751 			    "fileno before     = %d\n"
10752 			    "blkno before      = %d\n",
10753 			    space_strs[sp->pkt_cdbp[1] & 7],
10754 			    bp->b_bcount,
10755 			    count, resid, done,
10756 			    un->un_pos.fileno, un->un_pos.blkno);
10757 
10758 			switch (sp->pkt_cdbp[1]) {
10759 			case SPACE_TYPE(SP_FLM):
10760 				/* Space file forward */
10761 				if (count >= 0) {
10762 					if (un->un_pos.eof <= ST_EOF) {
10763 						un->un_pos.eof = ST_NO_EOF;
10764 					}
10765 					un->un_pos.fileno += done;
10766 					un->un_pos.blkno = 0;
10767 					break;
10768 				}
10769 				/* Space file backward */
10770 				if (done > un->un_pos.fileno) {
10771 					un->un_pos.fileno = 0;
10772 					un->un_pos.blkno = 0;
10773 				} else {
10774 					un->un_pos.fileno -= done;
10775 					un->un_pos.blkno = INF;
10776 				}
10777 				break;
10778 			case SPACE_TYPE(SP_BLK):
10779 				/* Space block forward */
10780 				if (count >= 0) {
10781 					un->un_pos.blkno += done;
10782 					break;
10783 				}
10784 				/* Space block backward */
10785 				if (un->un_pos.eof >= ST_EOF_PENDING) {
10786 				/*
10787 				 * we stepped back into
10788 				 * a previous file; we are not
10789 				 * making an effort to pretend that
10790 				 * we are still in the current file
10791 				 * ie. logical == physical position
10792 				 * and leave it to st_ioctl to correct
10793 				 */
10794 					if (done > un->un_pos.blkno) {
10795 						un->un_pos.blkno = 0;
10796 					} else {
10797 						un->un_pos.fileno--;
10798 						un->un_pos.blkno = INF;
10799 					}
10800 				} else {
10801 					un->un_pos.blkno -= done;
10802 				}
10803 				break;
10804 			case SPACE_TYPE(SP_SQFLM):
10805 				un->un_pos.pmode = logical;
10806 				un->un_pos.blkno = 0;
10807 				un->un_lastop = new_lastop = ST_OP_CTL;
10808 				break;
10809 			case SPACE_TYPE(SP_EOD):
10810 				un->un_pos.pmode = logical;
10811 				un->un_pos.eof = ST_EOM;
10812 				un->un_status = KEY_BLANK_CHECK;
10813 				break;
10814 			default:
10815 				un->un_pos.pmode = invalid;
10816 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
10817 				    "Unsupported space cmd: %s\n",
10818 				    space_strs[sp->pkt_cdbp[1] & 7]);
10819 
10820 				un->un_lastop = new_lastop = ST_OP_CTL;
10821 			}
10822 
10823 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10824 			    "after_space rs %ld fil %d blk %d\n",
10825 			    resid, un->un_pos.fileno, un->un_pos.blkno);
10826 
10827 			break;
10828 		}
10829 		case SCMD_LOAD:
10830 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
10831 				un->un_pos.fileno = 0;
10832 				un->un_pos.pmode = legacy;
10833 			} else {
10834 				un->un_state = ST_STATE_OFFLINE;
10835 				un->un_pos.pmode = invalid;
10836 			}
10837 			un->un_density_known = 0;
10838 			un->un_pos.eof = ST_NO_EOF;
10839 			un->un_pos.blkno = 0;
10840 			un->un_lastop = new_lastop = ST_OP_CTL;
10841 			break;
10842 		case SCMD_ERASE:
10843 			un->un_pos.eof = ST_NO_EOF;
10844 			un->un_pos.blkno = 0;
10845 			un->un_pos.fileno = 0;
10846 			un->un_pos.lgclblkno = 0;
10847 			un->un_pos.pmode = legacy;
10848 			new_lastop = ST_OP_CTL;
10849 			break;
10850 		case SCMD_RESERVE:
10851 			un->un_rsvd_status |= ST_RESERVE;
10852 			un->un_rsvd_status &=
10853 			    ~(ST_RELEASE | ST_LOST_RESERVE |
10854 			    ST_RESERVATION_CONFLICT);
10855 			new_lastop = un->un_lastop;
10856 			break;
10857 		case SCMD_RELEASE:
10858 			un->un_rsvd_status |= ST_RELEASE;
10859 			un->un_rsvd_status &=
10860 			    ~(ST_RESERVE | ST_LOST_RESERVE |
10861 			    ST_RESERVATION_CONFLICT);
10862 			new_lastop = ST_OP_CTL;
10863 			break;
10864 		case SCMD_PERSISTENT_RESERVE_IN:
10865 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10866 			    "PGR_IN command\n");
10867 			break;
10868 		case SCMD_PERSISTENT_RESERVE_OUT:
10869 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
10870 			case ST_SA_SCSI3_RESERVE:
10871 			case ST_SA_SCSI3_PREEMPT:
10872 			case ST_SA_SCSI3_PREEMPTANDABORT:
10873 				un->un_rsvd_status |=
10874 				    ST_APPLICATION_RESERVATIONS;
10875 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10876 				    "PGR Reserve and set: entering"
10877 				    " ST_APPLICATION_RESERVATIONS mode");
10878 				break;
10879 			case ST_SA_SCSI3_RELEASE:
10880 			case ST_SA_SCSI3_CLEAR:
10881 				un->un_rsvd_status &=
10882 				    ~ST_APPLICATION_RESERVATIONS;
10883 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10884 				    "PGR Release and reset: exiting"
10885 				    " ST_APPLICATION_RESERVATIONS mode");
10886 				break;
10887 			}
10888 			break;
10889 		case SCMD_TEST_UNIT_READY:
10890 		case SCMD_READ_BLKLIM:
10891 		case SCMD_REQUEST_SENSE:
10892 		case SCMD_INQUIRY:
10893 		case SCMD_RECOVER_BUF:
10894 		case SCMD_MODE_SELECT:
10895 		case SCMD_MODE_SENSE:
10896 		case SCMD_DOORLOCK:
10897 		case SCMD_READ_BUFFER:
10898 		case SCMD_REPORT_DENSITIES:
10899 		case SCMD_LOG_SELECT_G1:
10900 		case SCMD_LOG_SENSE_G1:
10901 		case SCMD_REPORT_LUNS:
10902 		case SCMD_READ_ATTRIBUTE:
10903 		case SCMD_READ_MEDIA_SERIAL:
10904 			new_lastop = ST_OP_CTL;
10905 			break;
10906 		case SCMD_READ_POSITION:
10907 			new_lastop = ST_OP_CTL;
10908 			if (USCSI_CMD(bp)) {
10909 				(void) st_get_read_pos(un, bp);
10910 			}
10911 			break;
10912 		case SCMD_LOCATE:
10913 		case SCMD_LOCATE_G4:
10914 			/* Locate makes position mode no longer legacy */
10915 			un->un_lastop = new_lastop = ST_OP_CTL;
10916 			break;
10917 		default:
10918 			/*
10919 			 * Unknown command, If was USCSI and USCSI_SILENT
10920 			 * flag was not set, set position to unknown.
10921 			 */
10922 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
10923 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
10924 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10925 				    "unknown cmd 0x%X caused loss of state\n",
10926 				    cmd);
10927 			} else {
10928 				break;
10929 			}
10930 			/* FALLTHROUGH */
10931 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
10932 			un->un_pos.pmode = invalid;
10933 			un->un_lastop = new_lastop = ST_OP_CTL;
10934 			break;
10935 		}
10936 
10937 		/* new_lastop should have been changed */
10938 		ASSERT(new_lastop != ST_OP_NIL);
10939 
10940 		/* If un_lastop should copy new_lastop  */
10941 		if (((un->un_lastop == ST_OP_WRITE) ||
10942 		    (un->un_lastop == ST_OP_WEOF)) &&
10943 		    new_lastop != ST_OP_CTL) {
10944 			un->un_lastop = new_lastop;
10945 		}
10946 	}
10947 
10948 	/*
10949 	 * In the st driver we have a logical and physical file position.
10950 	 * Under BSD behavior, when you get a zero read, the logical position
10951 	 * is before the filemark but after the last record of the file.
10952 	 * The physical position is after the filemark. MTIOCGET should always
10953 	 * return the logical file position.
10954 	 *
10955 	 * The next read gives a silent skip to the next file.
10956 	 * Under SVR4, the logical file position remains before the filemark
10957 	 * until the file is closed or a space operation is performed.
10958 	 * Hence set err_resid and err_file before changing fileno if case
10959 	 * BSD Behaviour.
10960 	 */
10961 	un->un_err_resid = bp->b_resid;
10962 	COPY_POS(&un->un_err_pos, &un->un_pos);
10963 	un->un_retry_ct = 0;
10964 
10965 
10966 	/*
10967 	 * If we've seen a filemark via the last read operation
10968 	 * advance the file counter, but mark things such that
10969 	 * the next read operation gets a zero count. We have
10970 	 * to put this here to handle the case of sitting right
10971 	 * at the end of a tape file having seen the file mark,
10972 	 * but the tape is closed and then re-opened without
10973 	 * any further i/o. That is, the position information
10974 	 * must be updated before a close.
10975 	 */
10976 
10977 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
10978 		/*
10979 		 * If we're a 1/2" tape, and we get a filemark
10980 		 * right on block 0, *AND* we were not in the
10981 		 * first file on the tape, and we've hit logical EOM.
10982 		 * We'll mark the state so that later we do the
10983 		 * right thing (in st_close(), st_strategy() or
10984 		 * st_ioctl()).
10985 		 *
10986 		 */
10987 		if ((un->un_dp->options & ST_REEL) &&
10988 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10989 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
10990 			un->un_pos.eof = ST_EOT_PENDING;
10991 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10992 			    "eot pending\n");
10993 			un->un_pos.fileno++;
10994 			un->un_pos.blkno = 0;
10995 		} else if (BSD_BEHAVIOR) {
10996 			/*
10997 			 * If the read of the filemark was a side effect
10998 			 * of reading some blocks (i.e., data was actually
10999 			 * read), then the EOF mark is pending and the
11000 			 * bump into the next file awaits the next read
11001 			 * operation (which will return a zero count), or
11002 			 * a close or a space operation, else the bump
11003 			 * into the next file occurs now.
11004 			 */
11005 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11006 			    "resid=%lx, bcount=%lx\n",
11007 			    bp->b_resid, bp->b_bcount);
11008 
11009 			if (bp->b_resid != bp->b_bcount) {
11010 				un->un_pos.eof = ST_EOF;
11011 			} else {
11012 				un->un_silent_skip = 1;
11013 				un->un_pos.eof = ST_NO_EOF;
11014 				un->un_pos.fileno++;
11015 				un->un_pos.lgclblkno++;
11016 				un->un_save_blkno = un->un_pos.blkno;
11017 				un->un_pos.blkno = 0;
11018 			}
11019 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11020 			    "eof of file %d, eof=%d\n",
11021 			    un->un_pos.fileno, un->un_pos.eof);
11022 		} else if (SVR4_BEHAVIOR) {
11023 			/*
11024 			 * If the read of the filemark was a side effect
11025 			 * of reading some blocks (i.e., data was actually
11026 			 * read), then the next read should return 0
11027 			 */
11028 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11029 			    "resid=%lx, bcount=%lx\n",
11030 			    bp->b_resid, bp->b_bcount);
11031 			if (bp->b_resid == bp->b_bcount) {
11032 				un->un_pos.eof = ST_EOF;
11033 			}
11034 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11035 			    "eof of file=%d, eof=%d\n",
11036 			    un->un_pos.fileno, un->un_pos.eof);
11037 		}
11038 	}
11039 }
11040 
11041 /*
11042  * set the correct un_errno, to take corner cases into consideration
11043  */
11044 static void
11045 st_set_pe_errno(struct scsi_tape *un)
11046 {
11047 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
11048 
11049 	ASSERT(mutex_owned(ST_MUTEX));
11050 
11051 	/* if errno is already set, don't reset it */
11052 	if (un->un_errno)
11053 		return;
11054 
11055 	/* here un_errno == 0 */
11056 	/*
11057 	 * if the last transfer before flushing all the
11058 	 * waiting I/O's, was 0 (resid = count), then we
11059 	 * want to give the user an error on all the rest,
11060 	 * so here.  If there was a transfer, we set the
11061 	 * resid and counts to 0, and let it drop through,
11062 	 * giving a zero return.  the next I/O will then
11063 	 * give an error.
11064 	 */
11065 	if (un->un_last_resid == un->un_last_count) {
11066 		switch (un->un_pos.eof) {
11067 		case ST_EOM:
11068 			un->un_errno = ENOMEM;
11069 			break;
11070 		case ST_EOT:
11071 		case ST_EOF:
11072 			un->un_errno = EIO;
11073 			break;
11074 		}
11075 	} else {
11076 		/*
11077 		 * we know they did not have a zero, so make
11078 		 * sure they get one
11079 		 */
11080 		un->un_last_resid = un->un_last_count = 0;
11081 	}
11082 }
11083 
11084 
11085 /*
11086  * send in a marker pkt to terminate flushing of commands by BBA (via
11087  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
11088  */
11089 static void
11090 st_hba_unflush(struct scsi_tape *un)
11091 {
11092 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
11093 
11094 	ASSERT(mutex_owned(ST_MUTEX));
11095 
11096 	if (!un->un_flush_on_errors)
11097 		return;
11098 
11099 #ifdef FLUSH_ON_ERRORS
11100 
11101 	if (!un->un_mkr_pkt) {
11102 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
11103 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
11104 
11105 		/* we slept, so it must be there */
11106 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
11107 	}
11108 
11109 	mutex_exit(ST_MUTEX);
11110 	scsi_transport(un->un_mkr_pkt);
11111 	mutex_enter(ST_MUTEX);
11112 #endif
11113 }
11114 
11115 static char *
11116 st_print_scsi_cmd(char cmd)
11117 {
11118 	char tmp[64];
11119 	char *cpnt;
11120 
11121 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
11122 	/* tmp goes out of scope on return and caller sees garbage */
11123 	if (cpnt == tmp) {
11124 		cpnt = "Unknown Command";
11125 	}
11126 	return (cpnt);
11127 }
11128 
11129 static void
11130 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
11131     char *title, char *cdb)
11132 {
11133 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
11134 	char buf[256];
11135 	int instance = ddi_get_instance(dip);
11136 	struct scsi_tape *un;
11137 
11138 	un = ddi_get_soft_state(st_state, instance);
11139 
11140 	ST_FUNC(dip, st_print_cdb);
11141 
11142 #ifdef DEBUG
11143 	if ((st_debug & 0x180) == 0x100) {
11144 		scsi_log(dip, label, level, "node %s cmd %s\n",
11145 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
11146 		return;
11147 	}
11148 #endif
11149 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
11150 	st_clean_print(dip, label, level, buf, cdb, len);
11151 }
11152 
11153 static void
11154 st_clean_print(dev_info_t *dev, char *label, uint_t level,
11155     char *title, char *data, int len)
11156 {
11157 	int	i;
11158 	int 	c;
11159 	char	*format;
11160 	char	buf[256];
11161 	uchar_t	byte;
11162 
11163 	ST_FUNC(dev, st_clean_print);
11164 
11165 	(void) sprintf(buf, "%s:\n", title);
11166 	scsi_log(dev, label, level, "%s", buf);
11167 	level = CE_CONT;
11168 	for (i = 0; i < len; ) {
11169 		buf[0] = 0;
11170 		for (c = 0; c < 8 && i < len; c++, i++) {
11171 			byte = (uchar_t)data[i];
11172 			if (byte < 0x10)
11173 				format = "0x0%x ";
11174 			else
11175 				format = "0x%x ";
11176 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
11177 		}
11178 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
11179 
11180 		scsi_log(dev, label, level, "%s\n", buf);
11181 	}
11182 }
11183 
11184 /*
11185  * Conditionally enabled debugging
11186  */
11187 #ifdef	STDEBUG
11188 static void
11189 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
11190 {
11191 	char tmpbuf[64];
11192 
11193 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
11194 
11195 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11196 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
11197 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
11198 	    count, count,
11199 	    wait == ASYNC_CMD ? "a" : "");
11200 }
11201 
11202 /*
11203  * Returns pointer to name of minor node name of device 'dev'.
11204  */
11205 static char *
11206 st_dev_name(dev_t dev)
11207 {
11208 	struct scsi_tape *un;
11209 	const char density[] = { 'l', 'm', 'h', 'c' };
11210 	static char name[4];
11211 	minor_t minor;
11212 	int instance;
11213 	int nprt = 0;
11214 
11215 	minor = getminor(dev);
11216 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
11217 	un = ddi_get_soft_state(st_state, instance);
11218 	if (un) {
11219 		ST_FUNC(ST_DEVINFO, st_dev_name);
11220 	}
11221 
11222 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
11223 
11224 	if (minor & MT_BSD) {
11225 		name[++nprt] = 'b';
11226 	}
11227 
11228 	if (minor & MT_NOREWIND) {
11229 		name[++nprt] = 'n';
11230 	}
11231 
11232 	/* NULL terminator */
11233 	name[++nprt] = 0;
11234 
11235 	return (name);
11236 }
11237 #endif	/* STDEBUG */
11238 
11239 /*
11240  * Soft error reporting, so far unique to each drive
11241  *
11242  * Currently supported: exabyte and DAT soft error reporting
11243  */
11244 static int
11245 st_report_exabyte_soft_errors(dev_t dev, int flag)
11246 {
11247 	uchar_t *sensep;
11248 	int amt;
11249 	int rval = 0;
11250 	char cdb[CDB_GROUP0], *c = cdb;
11251 	struct uscsi_cmd *com;
11252 
11253 	GET_SOFT_STATE(dev);
11254 
11255 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
11256 
11257 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11258 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
11259 	    dev, flag);
11260 
11261 	ASSERT(mutex_owned(ST_MUTEX));
11262 
11263 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11264 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
11265 
11266 	*c++ = SCMD_REQUEST_SENSE;
11267 	*c++ = 0;
11268 	*c++ = 0;
11269 	*c++ = 0;
11270 	*c++ = TAPE_SENSE_LENGTH;
11271 	/*
11272 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
11273 	 */
11274 	*c   = (char)0x80;
11275 
11276 	com->uscsi_cdb = cdb;
11277 	com->uscsi_cdblen = CDB_GROUP0;
11278 	com->uscsi_bufaddr = (caddr_t)sensep;
11279 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
11280 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11281 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11282 
11283 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11284 	if (rval || com->uscsi_status) {
11285 		goto done;
11286 	}
11287 
11288 	/*
11289 	 * was there enough data?
11290 	 */
11291 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
11292 
11293 	if ((amt >= 19) && un->un_kbytes_xferred) {
11294 		uint_t count, error_rate;
11295 		uint_t rate;
11296 
11297 		if (sensep[21] & CLN) {
11298 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11299 			    "Periodic head cleaning required");
11300 		}
11301 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
11302 			goto done;
11303 		}
11304 		/*
11305 		 * check if soft error reporting needs to be done.
11306 		 */
11307 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
11308 		count &= 0xffffff;
11309 		error_rate = (count * 100)/un->un_kbytes_xferred;
11310 
11311 #ifdef	STDEBUG
11312 		if (st_soft_error_report_debug) {
11313 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11314 			    "Exabyte Soft Error Report:\n");
11315 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11316 			    "read/write error counter: %d\n", count);
11317 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11318 			    "number of bytes transferred: %dK\n",
11319 			    un->un_kbytes_xferred);
11320 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11321 			    "error_rate: %d%%\n", error_rate);
11322 
11323 			if (amt >= 22) {
11324 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11325 				    "unit sense: 0x%b 0x%b 0x%b\n",
11326 				    sensep[19], SENSE_19_BITS,
11327 				    sensep[20], SENSE_20_BITS,
11328 				    sensep[21], SENSE_21_BITS);
11329 			}
11330 			if (amt >= 27) {
11331 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11332 				    "tracking retry counter: %d\n",
11333 				    sensep[26]);
11334 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11335 				    "read/write retry counter: %d\n",
11336 				    sensep[27]);
11337 			}
11338 		}
11339 #endif
11340 
11341 		if (flag & FWRITE) {
11342 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
11343 		} else {
11344 			rate = EXABYTE_READ_ERROR_THRESHOLD;
11345 		}
11346 		if (error_rate >= rate) {
11347 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11348 			    "Soft error rate (%d%%) during %s was too high",
11349 			    error_rate,
11350 			    ((flag & FWRITE) ? wrg_str : rdg_str));
11351 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11352 			    "Please, replace tape cartridge\n");
11353 		}
11354 	}
11355 
11356 done:
11357 	kmem_free(com, sizeof (*com));
11358 	kmem_free(sensep, TAPE_SENSE_LENGTH);
11359 
11360 	if (rval != 0) {
11361 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11362 		    "exabyte soft error reporting failed\n");
11363 	}
11364 	return (rval);
11365 }
11366 
11367 /*
11368  * this is very specific to Archive 4mm dat
11369  */
11370 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
11371 
11372 static int
11373 st_report_dat_soft_errors(dev_t dev, int flag)
11374 {
11375 	uchar_t *sensep;
11376 	int amt, i;
11377 	int rval = 0;
11378 	char cdb[CDB_GROUP1], *c = cdb;
11379 	struct uscsi_cmd *com;
11380 
11381 	GET_SOFT_STATE(dev);
11382 
11383 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
11384 
11385 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11386 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11387 
11388 	ASSERT(mutex_owned(ST_MUTEX));
11389 
11390 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11391 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11392 
11393 	*c++ = SCMD_LOG_SENSE_G1;
11394 	*c++ = 0;
11395 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
11396 	*c++ = 0;
11397 	*c++ = 0;
11398 	*c++ = 0;
11399 	*c++ = 2;
11400 	*c++ = 0;
11401 	*c++ = (char)LOG_SENSE_LENGTH;
11402 	*c   = 0;
11403 	com->uscsi_cdb    = cdb;
11404 	com->uscsi_cdblen  = CDB_GROUP1;
11405 	com->uscsi_bufaddr = (caddr_t)sensep;
11406 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
11407 	com->uscsi_flags   =
11408 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11409 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11410 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11411 	if (rval) {
11412 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11413 		    "DAT soft error reporting failed\n");
11414 	}
11415 	if (rval || com->uscsi_status) {
11416 		goto done;
11417 	}
11418 
11419 	/*
11420 	 * was there enough data?
11421 	 */
11422 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
11423 
11424 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
11425 		int total, retries, param_code;
11426 
11427 		total = -1;
11428 		retries = -1;
11429 		amt = sensep[3] + 4;
11430 
11431 
11432 #ifdef STDEBUG
11433 		if (st_soft_error_report_debug) {
11434 			(void) printf("logsense:");
11435 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
11436 				if (i % 16 == 0) {
11437 					(void) printf("\t\n");
11438 				}
11439 				(void) printf(" %x", sensep[i]);
11440 			}
11441 			(void) printf("\n");
11442 		}
11443 #endif
11444 
11445 		/*
11446 		 * parse the param_codes
11447 		 */
11448 		if (sensep[0] == 2 || sensep[0] == 3) {
11449 			for (i = 4; i < amt; i++) {
11450 				param_code = (sensep[i++] << 8);
11451 				param_code += sensep[i++];
11452 				i++; /* skip control byte */
11453 				if (param_code == 5) {
11454 					if (sensep[i++] == 4) {
11455 						total = (sensep[i++] << 24);
11456 						total += (sensep[i++] << 16);
11457 						total += (sensep[i++] << 8);
11458 						total += sensep[i];
11459 					}
11460 				} else if (param_code == 0x8007) {
11461 					if (sensep[i++] == 2) {
11462 						retries = sensep[i++] << 8;
11463 						retries += sensep[i];
11464 					}
11465 				} else {
11466 					i += sensep[i];
11467 				}
11468 			}
11469 		}
11470 
11471 		/*
11472 		 * if the log sense returned valid numbers then determine
11473 		 * the read and write error thresholds based on the amount of
11474 		 * data transferred
11475 		 */
11476 
11477 		if (total > 0 && retries > 0) {
11478 			short normal_retries = 0;
11479 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
11480 			    "total xferred (%s) =%x, retries=%x\n",
11481 			    ((flag & FWRITE) ? wrg_str : rdg_str),
11482 			    total, retries);
11483 
11484 			if (flag & FWRITE) {
11485 				if (total <=
11486 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
11487 					normal_retries =
11488 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
11489 				} else {
11490 					normal_retries =
11491 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
11492 				}
11493 			} else {
11494 				if (total <=
11495 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
11496 					normal_retries =
11497 					    DAT_SMALL_READ_ERROR_THRESHOLD;
11498 				} else {
11499 					normal_retries =
11500 					    DAT_LARGE_READ_ERROR_THRESHOLD;
11501 				}
11502 			}
11503 
11504 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
11505 			"normal retries=%d\n", normal_retries);
11506 
11507 			if (retries >= normal_retries) {
11508 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11509 				    "Soft error rate (retries = %d) during "
11510 				    "%s was too high",  retries,
11511 				    ((flag & FWRITE) ? wrg_str : rdg_str));
11512 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11513 				    "Periodic head cleaning required "
11514 				    "and/or replace tape cartridge\n");
11515 			}
11516 
11517 		} else if (total == -1 || retries == -1) {
11518 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11519 			    "log sense parameter code does not make sense\n");
11520 		}
11521 	}
11522 
11523 	/*
11524 	 * reset all values
11525 	 */
11526 	c = cdb;
11527 	*c++ = SCMD_LOG_SELECT_G1;
11528 	*c++ = 2;	/* this resets all values */
11529 	*c++ = (char)0xc0;
11530 	*c++ = 0;
11531 	*c++ = 0;
11532 	*c++ = 0;
11533 	*c++ = 0;
11534 	*c++ = 0;
11535 	*c++ = 0;
11536 	*c   = 0;
11537 	com->uscsi_bufaddr = NULL;
11538 	com->uscsi_buflen  = 0;
11539 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
11540 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11541 	if (rval) {
11542 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11543 		    "DAT soft error reset failed\n");
11544 	}
11545 done:
11546 	kmem_free(com, sizeof (*com));
11547 	kmem_free(sensep, LOG_SENSE_LENGTH);
11548 	return (rval);
11549 }
11550 
11551 static int
11552 st_report_soft_errors(dev_t dev, int flag)
11553 {
11554 	GET_SOFT_STATE(dev);
11555 
11556 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
11557 
11558 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11559 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11560 
11561 	ASSERT(mutex_owned(ST_MUTEX));
11562 
11563 	switch (un->un_dp->type) {
11564 	case ST_TYPE_EXB8500:
11565 	case ST_TYPE_EXABYTE:
11566 		return (st_report_exabyte_soft_errors(dev, flag));
11567 		/*NOTREACHED*/
11568 	case ST_TYPE_PYTHON:
11569 		return (st_report_dat_soft_errors(dev, flag));
11570 		/*NOTREACHED*/
11571 	default:
11572 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
11573 		return (-1);
11574 	}
11575 }
11576 
11577 /*
11578  * persistent error routines
11579  */
11580 
11581 /*
11582  * enable persistent errors, and set the throttle appropriately, checking
11583  * for flush-on-errors capability
11584  */
11585 static void
11586 st_turn_pe_on(struct scsi_tape *un)
11587 {
11588 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
11589 
11590 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
11591 	ASSERT(mutex_owned(ST_MUTEX));
11592 
11593 	un->un_persistence = 1;
11594 
11595 	/*
11596 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
11597 	 * enabled.  This will simplify the error handling for request senses
11598 	 */
11599 
11600 	if (un->un_arq_enabled && un->un_untagged_qing) {
11601 		uchar_t f_o_e;
11602 
11603 		mutex_exit(ST_MUTEX);
11604 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
11605 		    1 : 0;
11606 		mutex_enter(ST_MUTEX);
11607 
11608 		un->un_flush_on_errors = f_o_e;
11609 	} else {
11610 		un->un_flush_on_errors = 0;
11611 	}
11612 
11613 	if (un->un_flush_on_errors)
11614 		un->un_max_throttle = (uchar_t)st_max_throttle;
11615 	else
11616 		un->un_max_throttle = 1;
11617 
11618 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
11619 		un->un_max_throttle = 1;
11620 
11621 	/* this will send a marker pkt */
11622 	CLEAR_PE(un);
11623 }
11624 
11625 /*
11626  * This turns persistent errors permanently off
11627  */
11628 static void
11629 st_turn_pe_off(struct scsi_tape *un)
11630 {
11631 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
11632 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
11633 	ASSERT(mutex_owned(ST_MUTEX));
11634 
11635 	/* turn it off for good */
11636 	un->un_persistence = 0;
11637 
11638 	/* this will send a marker pkt */
11639 	CLEAR_PE(un);
11640 
11641 	/* turn off flush on error capability, if enabled */
11642 	if (un->un_flush_on_errors) {
11643 		mutex_exit(ST_MUTEX);
11644 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
11645 		mutex_enter(ST_MUTEX);
11646 	}
11647 
11648 
11649 	un->un_flush_on_errors = 0;
11650 }
11651 
11652 /*
11653  * This clear persistent errors, allowing more commands through, and also
11654  * sending a marker packet.
11655  */
11656 static void
11657 st_clear_pe(struct scsi_tape *un)
11658 {
11659 	ST_FUNC(ST_DEVINFO, st_clear_pe);
11660 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
11661 	ASSERT(mutex_owned(ST_MUTEX));
11662 
11663 	un->un_persist_errors = 0;
11664 	un->un_throttle = un->un_last_throttle = 1;
11665 	un->un_errno = 0;
11666 	st_hba_unflush(un);
11667 }
11668 
11669 /*
11670  * This will flag persistent errors, shutting everything down, if the
11671  * application had enabled persistent errors via MTIOCPERSISTENT
11672  */
11673 static void
11674 st_set_pe_flag(struct scsi_tape *un)
11675 {
11676 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
11677 	ASSERT(mutex_owned(ST_MUTEX));
11678 
11679 	if (un->un_persistence) {
11680 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
11681 		un->un_persist_errors = 1;
11682 		un->un_throttle = un->un_last_throttle = 0;
11683 	}
11684 }
11685 
11686 /*
11687  * List of commands that are allowed to be done while another host holds
11688  * the reservation.
11689  */
11690 struct {
11691 	uchar_t cmd;
11692 	uchar_t byte;	/* byte to look for data */
11693 	uint32_t mask;	/* bits that matter in the above data */
11694 } rcmds[] = {
11695 	{ SCMD_TEST_UNIT_READY, 0, 0 }, /* may fail on older drives */
11696 	{ SCMD_REQUEST_SENSE, 0, 0 },
11697 	{ SCMD_READ_BLKLIM, 0, 0 },
11698 	{ SCMD_INQUIRY, 0, 0 },
11699 	{ SCMD_RESERVE, 0, 0 },
11700 	{ SCMD_RELEASE, 0, 0 },
11701 	{ SCMD_DOORLOCK, 4, 3 },	/* allow (unlock) media access only */
11702 	{ SCMD_REPORT_DENSITIES, 0, 0 },
11703 	{ SCMD_LOG_SENSE_G1, 0, 0 },
11704 	{ SCMD_PERSISTENT_RESERVE_IN, 0, 0 },
11705 	{ SCMD_PERSISTENT_RESERVE_OUT, 0, 0 },
11706 	{ SCMD_REPORT_LUNS, 0, 0 }
11707 };
11708 
11709 static int
11710 st_do_reserve(struct scsi_tape *un)
11711 {
11712 	int rval;
11713 
11714 	ST_FUNC(ST_DEVINFO, st_do_reserve);
11715 
11716 	/*
11717 	 * Issue a Throw-Away reserve command to clear the
11718 	 * check condition.
11719 	 * If the current behaviour of reserve/release is to
11720 	 * hold reservation across opens , and if a Bus reset
11721 	 * has been issued between opens then this command
11722 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
11723 	 * In this case return an EACCES so that user knows that
11724 	 * reservation has been lost in between opens.
11725 	 * If this error is not returned and we continue with
11726 	 * successful open , then user may think position of the
11727 	 * tape is still the same but inreality we would rewind the
11728 	 * tape and continue from BOT.
11729 	 */
11730 	rval = st_reserve_release(un, ST_RESERVE);
11731 	if (rval) {
11732 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
11733 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
11734 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
11735 			un->un_errno = EACCES;
11736 			return (EACCES);
11737 		}
11738 		rval = st_reserve_release(un, ST_RESERVE);
11739 	}
11740 	if (rval == 0) {
11741 		un->un_rsvd_status |= ST_INIT_RESERVE;
11742 	}
11743 
11744 	return (rval);
11745 }
11746 
11747 static int
11748 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb)
11749 {
11750 	int i;
11751 	int rval = 0;
11752 
11753 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
11754 
11755 	/*
11756 	 * If already reserved no need to do it again.
11757 	 * Also if Reserve and Release are disabled Just return.
11758 	 */
11759 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11760 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11761 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11762 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
11763 		    st_print_scsi_cmd((uchar_t)cdb[0]));
11764 		return (0);
11765 	}
11766 
11767 	/* See if command is on the list */
11768 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11769 		if ((uchar_t)cdb[0] == rcmds[i].cmd) {
11770 			/*
11771 			 * cmd is on list.
11772 			 * if byte is zero always allowed.
11773 			 */
11774 			if (rcmds[i].byte == 0) {
11775 				return (rval);
11776 			}
11777 			if (((cdb[rcmds[i].byte]) & (rcmds[i].mask)) == 0) {
11778 				return (rval);
11779 			}
11780 			break;
11781 		}
11782 	}
11783 
11784 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11785 	    "Command %s requires reservation", st_print_scsi_cmd(cdb[0]));
11786 
11787 	rval = st_do_reserve(un);
11788 
11789 	return (rval);
11790 }
11791 
11792 static int
11793 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
11794 {
11795 	int i;
11796 	int rval = 0;
11797 
11798 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
11799 
11800 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11801 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11802 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11803 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
11804 		    st_print_scsi_cmd(cmd));
11805 		return (0);
11806 	}
11807 
11808 	/* See if command is on the list */
11809 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11810 		if (cmd == rcmds[i].cmd) {
11811 			/*
11812 			 * cmd is on list.
11813 			 * if byte is zero always allowed.
11814 			 */
11815 			if (rcmds[i].byte == 0) {
11816 				return (rval);
11817 			}
11818 			if (((rcmds[i].mask) & cnt) == 0) {
11819 				return (rval);
11820 			}
11821 			break;
11822 		}
11823 	}
11824 
11825 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11826 	    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
11827 
11828 	rval = st_do_reserve(un);
11829 
11830 	return (rval);
11831 }
11832 
11833 static int
11834 st_reserve_release(struct scsi_tape *un, int cmd)
11835 {
11836 	struct uscsi_cmd	uscsi_cmd;
11837 	struct uscsi_cmd	*com = &uscsi_cmd;
11838 	int			rval;
11839 	char			cdb[CDB_GROUP0];
11840 
11841 
11842 
11843 	ST_FUNC(ST_DEVINFO, st_reserve_release);
11844 
11845 	ASSERT(mutex_owned(ST_MUTEX));
11846 
11847 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11848 	    "st_reserve_release: %s \n",
11849 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
11850 
11851 	bzero(cdb, CDB_GROUP0);
11852 	if (cmd == ST_RELEASE) {
11853 		cdb[0] = SCMD_RELEASE;
11854 	} else {
11855 		cdb[0] = SCMD_RESERVE;
11856 	}
11857 	bzero(com, sizeof (struct uscsi_cmd));
11858 	com->uscsi_flags = USCSI_WRITE;
11859 	com->uscsi_cdb = cdb;
11860 	com->uscsi_cdblen = CDB_GROUP0;
11861 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11862 
11863 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
11864 
11865 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11866 	    "st_reserve_release: rval(1)=%d\n", rval);
11867 
11868 	if (rval) {
11869 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT) {
11870 			rval = EACCES;
11871 		}
11872 		/*
11873 		 * dynamically turn off reserve/release support
11874 		 * in case of drives which do not support
11875 		 * reserve/release command(ATAPI drives).
11876 		 */
11877 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
11878 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
11879 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
11880 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11881 				    "Tape unit does not support "
11882 				    "reserve/release \n");
11883 			}
11884 			rval = 0;
11885 		}
11886 	}
11887 	return (rval);
11888 }
11889 
11890 static int
11891 st_take_ownership(dev_t dev)
11892 {
11893 	int rval;
11894 
11895 	GET_SOFT_STATE(dev);
11896 
11897 	ST_FUNC(ST_DEVINFO, st_take_ownership);
11898 
11899 	ASSERT(mutex_owned(ST_MUTEX));
11900 
11901 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11902 	    "st_take_ownership: Entering ...\n");
11903 
11904 
11905 	rval = st_reserve_release(un, ST_RESERVE);
11906 	/*
11907 	 * XXX -> Should reset be done only if we get EACCES.
11908 	 * .
11909 	 */
11910 	if (rval) {
11911 		mutex_exit(ST_MUTEX);
11912 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
11913 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
11914 				mutex_enter(ST_MUTEX);
11915 				return (EIO);
11916 			}
11917 		}
11918 		mutex_enter(ST_MUTEX);
11919 		un->un_rsvd_status &=
11920 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
11921 
11922 		mutex_exit(ST_MUTEX);
11923 		delay(drv_usectohz(ST_RESERVATION_DELAY));
11924 		mutex_enter(ST_MUTEX);
11925 		/*
11926 		 * remove the check condition.
11927 		 */
11928 		(void) st_reserve_release(un, ST_RESERVE);
11929 		if ((rval = st_reserve_release(un, ST_RESERVE)) != 0) {
11930 			if ((st_reserve_release(un, ST_RESERVE)) != 0) {
11931 				rval = (un->un_rsvd_status &
11932 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
11933 				return (rval);
11934 			}
11935 		}
11936 		/*
11937 		 * Set tape state to ST_STATE_OFFLINE , in case if
11938 		 * the user wants to continue and start using
11939 		 * the tape.
11940 		 */
11941 		un->un_state = ST_STATE_OFFLINE;
11942 		un->un_rsvd_status |= ST_INIT_RESERVE;
11943 	}
11944 	return (rval);
11945 }
11946 
11947 static int
11948 st_create_errstats(struct scsi_tape *un, int instance)
11949 {
11950 	char	kstatname[KSTAT_STRLEN];
11951 
11952 	ST_FUNC(ST_DEVINFO, st_create_errstats);
11953 
11954 	/*
11955 	 * Create device error kstats
11956 	 */
11957 
11958 	if (un->un_errstats == (kstat_t *)0) {
11959 		(void) sprintf(kstatname, "st%d,err", instance);
11960 		un->un_errstats = kstat_create("sterr", instance, kstatname,
11961 		    "device_error", KSTAT_TYPE_NAMED,
11962 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
11963 		    KSTAT_FLAG_PERSISTENT);
11964 
11965 		if (un->un_errstats) {
11966 			struct st_errstats	*stp;
11967 
11968 			stp = (struct st_errstats *)un->un_errstats->ks_data;
11969 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
11970 			    KSTAT_DATA_ULONG);
11971 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
11972 			    KSTAT_DATA_ULONG);
11973 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
11974 			    KSTAT_DATA_ULONG);
11975 			kstat_named_init(&stp->st_vid, "Vendor",
11976 			    KSTAT_DATA_CHAR);
11977 			kstat_named_init(&stp->st_pid, "Product",
11978 			    KSTAT_DATA_CHAR);
11979 			kstat_named_init(&stp->st_revision, "Revision",
11980 			    KSTAT_DATA_CHAR);
11981 			kstat_named_init(&stp->st_serial, "Serial No",
11982 			    KSTAT_DATA_CHAR);
11983 			un->un_errstats->ks_private = un;
11984 			un->un_errstats->ks_update = nulldev;
11985 			kstat_install(un->un_errstats);
11986 			/*
11987 			 * Fill in the static data
11988 			 */
11989 			(void) strncpy(&stp->st_vid.value.c[0],
11990 			    ST_INQUIRY->inq_vid, 8);
11991 			/*
11992 			 * XXX:  Emulex MT-02 (and emulators) predates
11993 			 *	 SCSI-1 and has no vid & pid inquiry data.
11994 			 */
11995 			if (ST_INQUIRY->inq_len != 0) {
11996 				(void) strncpy(&stp->st_pid.value.c[0],
11997 				    ST_INQUIRY->inq_pid, 16);
11998 				(void) strncpy(&stp->st_revision.value.c[0],
11999 				    ST_INQUIRY->inq_revision, 4);
12000 				(void) strncpy(&stp->st_serial.value.c[0],
12001 				    ST_INQUIRY->inq_serial, 12);
12002 			}
12003 		}
12004 	}
12005 	return (0);
12006 }
12007 
12008 static int
12009 st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos)
12010 {
12011 	dev_t dev;
12012 	int rval;
12013 
12014 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
12015 
12016 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
12017 	ASSERT(mutex_owned(ST_MUTEX));
12018 
12019 	/* Can't restore an invalid position */
12020 	if (pos->pmode == invalid) {
12021 		return (4);
12022 	}
12023 
12024 	/*
12025 	 * Assumtions:
12026 	 *	If a position was read and is in logical position mode.
12027 	 *	If a drive supports read position it supports locate.
12028 	 *	If the read position type is not NO_POS. even though
12029 	 *	   a read position make not have been attemped yet.
12030 	 *
12031 	 *	The drive can locate to the position.
12032 	 */
12033 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
12034 		/*
12035 		 * If position mode is logical or legacy mode try
12036 		 * to locate there as it is faster.
12037 		 * If it fails try the old way.
12038 		 */
12039 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12040 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
12041 		    pos->lgclblkno);
12042 
12043 		if (st_logical_block_locate(un, pos->lgclblkno, pos->partition)
12044 		    == 0) {
12045 			/* Assume we are there copy rest of position back */
12046 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
12047 				COPY_POS(&un->un_pos, pos);
12048 			}
12049 			return (0);
12050 		}
12051 
12052 		/*
12053 		 * If logical block locate failed to restore a logical
12054 		 * position, can't recover.
12055 		 */
12056 		if (pos->pmode == logical) {
12057 			return (-1);
12058 		}
12059 	}
12060 
12061 	dev = un->un_dev;
12062 
12063 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12064 	    "Restoring tape position at fileno=%x, blkno=%x....",
12065 	    pos->fileno, pos->blkno);
12066 
12067 	/*
12068 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
12069 	 * so as not to rewind tape on RESETS: Gee, Has life ever
12070 	 * been simple in tape land ?
12071 	 */
12072 	rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
12073 	if (rval) {
12074 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12075 		"Failed to restore the last file and block position: In"
12076 		" this state, Tape will be loaded at BOT during next open");
12077 		un->un_pos.pmode = invalid;
12078 		return (rval);
12079 	}
12080 
12081 	/* If the position was as the result of back space file */
12082 	if (pos->blkno > (INF / 2)) {
12083 		/* Go one extra file forward */
12084 		pos->fileno++;
12085 		/* Figure how many blocks to back into the previous file */
12086 		pos->blkno = -(INF - pos->blkno);
12087 	}
12088 
12089 	/* Go to requested fileno */
12090 	if (pos->fileno) {
12091 		rval = st_cmd(dev, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
12092 		if (rval) {
12093 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12094 			    "Failed to restore the last file position: In this "
12095 			    " state, Tape will be loaded at BOT during next"
12096 			    " open %d", __LINE__);
12097 			un->un_pos.pmode = invalid;
12098 			pos->pmode = invalid;
12099 			return (rval);
12100 		}
12101 	}
12102 
12103 	/*
12104 	 * If backing into a file we already did an extra file forward.
12105 	 * Now we have to back over the filemark to get to the end of
12106 	 * the previous file. The blkno has been ajusted to a negative
12107 	 * value so we will get to the expected location.
12108 	 */
12109 	if (pos->blkno) {
12110 		rval = st_cmd(dev, SCMD_SPACE, Fmk(-1), SYNC_CMD);
12111 		if (rval) {
12112 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12113 			    "Failed to restore the last file position: In this "
12114 			    " state, Tape will be loaded at BOT during next"
12115 			    " open %d", __LINE__);
12116 			un->un_pos.pmode = invalid;
12117 			pos->pmode = invalid;
12118 			return (rval);
12119 		}
12120 	}
12121 
12122 	/*
12123 	 * The position mode, block and fileno should be correct,
12124 	 * This updates eof and logical position information.
12125 	 */
12126 	un->un_pos.eof = pos->eof;
12127 	un->un_pos.lgclblkno = pos->lgclblkno;
12128 
12129 	return (0);
12130 }
12131 
12132 /*
12133  * check sense key, ASC, ASCQ in order to determine if the tape needs
12134  * to be ejected
12135  */
12136 
12137 static int
12138 st_check_asc_ascq(struct scsi_tape *un)
12139 {
12140 	struct scsi_extended_sense *sensep = ST_RQSENSE;
12141 	struct tape_failure_code   *code;
12142 
12143 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
12144 
12145 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
12146 		if ((code->key  == sensep->es_key) &&
12147 		    (code->add_code  == sensep->es_add_code) &&
12148 		    (code->qual_code == sensep->es_qual_code))
12149 			return (1);
12150 	}
12151 	return (0);
12152 }
12153 
12154 /*
12155  * st_logpage_supported() sends a Log Sense command with
12156  * page code = 0 = Supported Log Pages Page to the device,
12157  * to see whether the page 'page' is supported.
12158  * Return values are:
12159  * -1 if the Log Sense command fails
12160  * 0 if page is not supported
12161  * 1 if page is supported
12162  */
12163 
12164 static int
12165 st_logpage_supported(dev_t dev, uchar_t page)
12166 {
12167 	uchar_t *sp, *sensep;
12168 	unsigned length;
12169 	struct uscsi_cmd *com;
12170 	int rval;
12171 	char cdb[CDB_GROUP1] = {
12172 		SCMD_LOG_SENSE_G1,
12173 		0,
12174 		SUPPORTED_LOG_PAGES_PAGE,
12175 		0,
12176 		0,
12177 		0,
12178 		0,
12179 		0,
12180 		(char)LOG_SENSE_LENGTH,
12181 		0
12182 	};
12183 
12184 	GET_SOFT_STATE(dev);
12185 
12186 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
12187 
12188 	ASSERT(mutex_owned(ST_MUTEX));
12189 
12190 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12191 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12192 
12193 	com->uscsi_cdb = cdb;
12194 	com->uscsi_cdblen = CDB_GROUP1;
12195 	com->uscsi_bufaddr = (caddr_t)sensep;
12196 	com->uscsi_buflen = LOG_SENSE_LENGTH;
12197 	com->uscsi_flags =
12198 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12199 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12200 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12201 	if (rval || com->uscsi_status) {
12202 		/* uscsi-command failed */
12203 		rval = -1;
12204 	} else {
12205 
12206 		sp = sensep + 3;
12207 
12208 		for (length = *sp++; length > 0; length--, sp++) {
12209 
12210 			if (*sp == page) {
12211 				rval = 1;
12212 				break;
12213 			}
12214 		}
12215 	}
12216 	kmem_free(com, sizeof (struct uscsi_cmd));
12217 	kmem_free(sensep, LOG_SENSE_LENGTH);
12218 	return (rval);
12219 }
12220 
12221 
12222 /*
12223  * st_check_clean_bit() gets the status of the tape's cleaning bit.
12224  *
12225  * If the device does support the TapeAlert log page, then the cleaning bit
12226  * information will be read from this page. Otherwise we will see if one of
12227  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
12228  * the device, which means, that we can get the cleaning bit information via
12229  * a RequestSense command.
12230  * If both methods of getting cleaning bit information are not supported
12231  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
12232  * returns with
12233  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
12234  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
12235  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
12236  * command fails, or if the amount of Request Sense data is not enough, then
12237  *  st_check_clean_bit() returns with -1.
12238  */
12239 
12240 static int
12241 st_check_clean_bit(dev_t dev)
12242 {
12243 	int rval = 0;
12244 
12245 	GET_SOFT_STATE(dev);
12246 
12247 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
12248 
12249 	ASSERT(mutex_owned(ST_MUTEX));
12250 
12251 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
12252 		return (rval);
12253 	}
12254 
12255 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12256 
12257 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
12258 		if (rval == 1) {
12259 
12260 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
12261 		}
12262 
12263 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
12264 		if (rval == 1) {
12265 
12266 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
12267 		}
12268 
12269 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12270 
12271 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
12272 		}
12273 	}
12274 
12275 	rval = 0;
12276 
12277 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
12278 
12279 		rval = st_check_sequential_clean_bit(dev);
12280 	}
12281 
12282 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
12283 
12284 		rval = st_check_alert_flags(dev);
12285 	}
12286 
12287 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
12288 
12289 		rval = st_check_sense_clean_bit(dev);
12290 	}
12291 
12292 	if (rval < 0) {
12293 		return (rval);
12294 	}
12295 
12296 	/*
12297 	 * If found a supported means to check need to clean.
12298 	 */
12299 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
12300 
12301 		/*
12302 		 * head needs to be cleaned.
12303 		 */
12304 		if (rval & MTF_TAPE_HEAD_DIRTY) {
12305 
12306 			/*
12307 			 * Print log message only first time
12308 			 * found needing cleaned.
12309 			 */
12310 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
12311 
12312 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12313 				    "Periodic head cleaning required");
12314 
12315 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
12316 			}
12317 
12318 		} else {
12319 
12320 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
12321 		}
12322 	}
12323 
12324 	return (rval);
12325 }
12326 
12327 
12328 static int
12329 st_check_sequential_clean_bit(dev_t dev)
12330 {
12331 	int rval;
12332 	int ix;
12333 	ushort_t parameter;
12334 	struct uscsi_cmd *cmd;
12335 	struct log_sequential_page *sp;
12336 	struct log_sequential_page_parameter *prm;
12337 	char cdb[CDB_GROUP1] = {
12338 		SCMD_LOG_SENSE_G1,
12339 		0,
12340 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
12341 		0,
12342 		0,
12343 		0,
12344 		0,
12345 		(char)(sizeof (struct log_sequential_page) >> 8),
12346 		(char)(sizeof (struct log_sequential_page)),
12347 		0
12348 	};
12349 
12350 	GET_SOFT_STATE(dev);
12351 
12352 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
12353 
12354 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12355 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
12356 
12357 	cmd->uscsi_flags   =
12358 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12359 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12360 	cmd->uscsi_cdb	   = cdb;
12361 	cmd->uscsi_cdblen  = CDB_GROUP1;
12362 	cmd->uscsi_bufaddr = (caddr_t)sp;
12363 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
12364 
12365 	rval = st_ioctl_cmd(dev, cmd, FKIOCTL);
12366 
12367 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
12368 
12369 		rval = -1;
12370 
12371 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
12372 
12373 		rval = -1;
12374 	}
12375 
12376 	prm = &sp->param[0];
12377 
12378 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
12379 
12380 		if (prm->log_param.length == 0) {
12381 			break;
12382 		}
12383 
12384 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
12385 		    (prm->log_param.pc_lo & 0xff));
12386 
12387 		if (parameter == SEQUENTIAL_NEED_CLN) {
12388 
12389 			rval = MTF_TAPE_CLN_SUPPORTED;
12390 			if (prm->param_value[prm->log_param.length - 1]) {
12391 
12392 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12393 				    "sequential log says head dirty\n");
12394 				rval |= MTF_TAPE_HEAD_DIRTY;
12395 			}
12396 		}
12397 		prm = (struct log_sequential_page_parameter *)
12398 		    &prm->param_value[prm->log_param.length];
12399 	}
12400 
12401 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12402 	kmem_free(sp,  sizeof (struct log_sequential_page));
12403 
12404 	return (rval);
12405 }
12406 
12407 
12408 static int
12409 st_check_alert_flags(dev_t dev)
12410 {
12411 	struct st_tape_alert *ta;
12412 	struct uscsi_cmd *com;
12413 	unsigned ix, length;
12414 	int rval;
12415 	tape_alert_flags flag;
12416 	char cdb[CDB_GROUP1] = {
12417 		SCMD_LOG_SENSE_G1,
12418 		0,
12419 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
12420 		0,
12421 		0,
12422 		0,
12423 		0,
12424 		(char)(sizeof (struct st_tape_alert) >> 8),
12425 		(char)(sizeof (struct st_tape_alert)),
12426 		0
12427 	};
12428 
12429 	GET_SOFT_STATE(dev);
12430 
12431 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
12432 
12433 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12434 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
12435 
12436 	com->uscsi_cdb = cdb;
12437 	com->uscsi_cdblen = CDB_GROUP1;
12438 	com->uscsi_bufaddr = (caddr_t)ta;
12439 	com->uscsi_buflen = sizeof (struct st_tape_alert);
12440 	com->uscsi_flags =
12441 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12442 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12443 
12444 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12445 
12446 	if (rval || com->uscsi_status || com->uscsi_resid) {
12447 
12448 		rval = -1; /* uscsi-command failed */
12449 
12450 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
12451 
12452 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12453 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
12454 		rval = -1;
12455 	}
12456 
12457 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
12458 
12459 
12460 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
12461 
12462 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12463 		    "TapeAlert length %d\n", length);
12464 	}
12465 
12466 
12467 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
12468 
12469 		/*
12470 		 * if rval is bad before the first pass don't bother
12471 		 */
12472 		if (ix == 0 && rval != 0) {
12473 
12474 			break;
12475 		}
12476 
12477 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
12478 		    ta->param[ix].log_param.pc_lo);
12479 
12480 		if ((ta->param[ix].param_value & 1) == 0) {
12481 			continue;
12482 		}
12483 		/*
12484 		 * check to see if current parameter is of interest.
12485 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
12486 		 */
12487 		if ((flag == TAF_CLEAN_NOW) ||
12488 		    (flag == TAF_CLEAN_PERIODIC) ||
12489 		    ((flag == CLEAN_FOR_ERRORS) &&
12490 		    (un->un_dp->type == ST_TYPE_STK9840))) {
12491 
12492 			rval = MTF_TAPE_CLN_SUPPORTED;
12493 
12494 
12495 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12496 			    "alert_page drive needs clean %d\n", flag);
12497 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
12498 			rval |= MTF_TAPE_HEAD_DIRTY;
12499 
12500 		} else if (flag == TAF_CLEANING_MEDIA) {
12501 
12502 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12503 			    "alert_page drive was cleaned\n");
12504 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
12505 		}
12506 
12507 	}
12508 
12509 	/*
12510 	 * Report it as dirty till we see it cleaned
12511 	 */
12512 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
12513 
12514 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12515 		    "alert_page still dirty\n");
12516 		rval |= MTF_TAPE_HEAD_DIRTY;
12517 	}
12518 
12519 	kmem_free(com, sizeof (struct uscsi_cmd));
12520 	kmem_free(ta,  sizeof (struct st_tape_alert));
12521 
12522 	return (rval);
12523 }
12524 
12525 
12526 static int
12527 st_check_sense_clean_bit(dev_t dev)
12528 {
12529 	uchar_t *sensep;
12530 	char cdb[CDB_GROUP0];
12531 	struct uscsi_cmd *com;
12532 	ushort_t byte_pos;
12533 	uchar_t bit_mask;
12534 	unsigned length;
12535 	int index;
12536 	int rval;
12537 
12538 	GET_SOFT_STATE(dev);
12539 
12540 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
12541 
12542 	/*
12543 	 * Since this tape does not support Tape Alert,
12544 	 * we now try to get the cleanbit status via
12545 	 * Request Sense.
12546 	 */
12547 
12548 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
12549 
12550 		index = 0;
12551 
12552 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
12553 
12554 		index = 1;
12555 
12556 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
12557 
12558 		index = 2;
12559 
12560 	} else {
12561 
12562 		return (-1);
12563 	}
12564 
12565 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
12566 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
12567 	length = byte_pos + 1;
12568 
12569 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12570 	sensep = kmem_zalloc(length, KM_SLEEP);
12571 
12572 	cdb[0] = SCMD_REQUEST_SENSE;
12573 	cdb[1] = 0;
12574 	cdb[2] = 0;
12575 	cdb[3] = 0;
12576 	cdb[4] = (char)length;
12577 	cdb[5] = 0;
12578 
12579 	com->uscsi_cdb = cdb;
12580 	com->uscsi_cdblen = CDB_GROUP0;
12581 	com->uscsi_bufaddr = (caddr_t)sensep;
12582 	com->uscsi_buflen = length;
12583 	com->uscsi_flags =
12584 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12585 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12586 
12587 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12588 
12589 	if (rval || com->uscsi_status || com->uscsi_resid) {
12590 
12591 		rval = -1;
12592 
12593 	} else {
12594 
12595 		rval = MTF_TAPE_CLN_SUPPORTED;
12596 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
12597 
12598 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12599 			    "sense data says head dirty\n");
12600 			rval |= MTF_TAPE_HEAD_DIRTY;
12601 		}
12602 	}
12603 
12604 	kmem_free(com, sizeof (struct uscsi_cmd));
12605 	kmem_free(sensep, length);
12606 	return (rval);
12607 }
12608 
12609 /*
12610  * st_clear_unit_attention
12611  *
12612  *  	run test unit ready's to clear out outstanding
12613  * 	unit attentions.
12614  * 	returns zero for SUCCESS or the errno from st_cmd call
12615  */
12616 static int
12617 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
12618 {
12619 	int	i    = 0;
12620 	int	rval;
12621 
12622 #ifdef DEBUG
12623 	GET_SOFT_STATE(dev_instance);
12624 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
12625 #endif
12626 
12627 	do {
12628 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
12629 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
12630 	return (rval);
12631 }
12632 
12633 static void
12634 st_calculate_timeouts(struct scsi_tape *un)
12635 {
12636 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
12637 
12638 	if (un->un_dp->non_motion_timeout == 0) {
12639 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12640 			un->un_dp->non_motion_timeout =
12641 			    st_io_time * st_long_timeout_x;
12642 		} else {
12643 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
12644 		}
12645 	}
12646 
12647 	if (un->un_dp->io_timeout == 0) {
12648 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12649 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
12650 		} else {
12651 			un->un_dp->io_timeout = (ushort_t)st_io_time;
12652 		}
12653 	}
12654 
12655 	if (un->un_dp->rewind_timeout == 0) {
12656 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12657 			un->un_dp->rewind_timeout =
12658 			    st_space_time * st_long_timeout_x;
12659 		} else {
12660 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
12661 		}
12662 	}
12663 
12664 	if (un->un_dp->space_timeout == 0) {
12665 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12666 			un->un_dp->space_timeout =
12667 			    st_space_time * st_long_timeout_x;
12668 		} else {
12669 			un->un_dp->space_timeout = (ushort_t)st_space_time;
12670 		}
12671 	}
12672 
12673 	if (un->un_dp->load_timeout == 0) {
12674 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12675 			un->un_dp->load_timeout =
12676 			    st_space_time * st_long_timeout_x;
12677 		} else {
12678 			un->un_dp->load_timeout = (ushort_t)st_space_time;
12679 		}
12680 	}
12681 
12682 	if (un->un_dp->unload_timeout == 0) {
12683 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12684 			un->un_dp->unload_timeout =
12685 			    st_space_time * st_long_timeout_x;
12686 		} else {
12687 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
12688 		}
12689 	}
12690 
12691 	if (un->un_dp->erase_timeout == 0) {
12692 		if (un->un_dp->options & ST_LONG_ERASE) {
12693 			un->un_dp->erase_timeout =
12694 			    st_space_time * st_long_space_time_x;
12695 		} else {
12696 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
12697 		}
12698 	}
12699 }
12700 
12701 
12702 static writablity
12703 st_is_not_wormable(struct scsi_tape *un)
12704 {
12705 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
12706 	return (RDWR);
12707 }
12708 
12709 static writablity
12710 st_is_hp_dat_tape_worm(struct scsi_tape *un)
12711 {
12712 	writablity wrt;
12713 
12714 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
12715 
12716 	/* Mode sense should be current */
12717 	if (un->un_mspl->media_type == 1) {
12718 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12719 		    "Drive has WORM media loaded\n");
12720 		wrt = WORM;
12721 	} else {
12722 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12723 		    "Drive has non WORM media loaded\n");
12724 		wrt = RDWR;
12725 	}
12726 	return (wrt);
12727 }
12728 
12729 #define	HP_DAT_INQUIRY 0x4A
12730 static writablity
12731 st_is_hp_dat_worm(struct scsi_tape *un)
12732 {
12733 	char *buf;
12734 	int result;
12735 	writablity wrt;
12736 
12737 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
12738 
12739 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
12740 
12741 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
12742 
12743 	if (result != 0) {
12744 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12745 		    "Read Standard Inquiry for WORM support failed");
12746 		wrt = FAILED;
12747 	} else if ((buf[40] & 1) == 0) {
12748 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12749 		    "Drive is NOT WORMable\n");
12750 		/* This drive doesn't support it so don't check again */
12751 		un->un_dp->options &= ~ST_WORMABLE;
12752 		wrt = RDWR;
12753 		un->un_wormable = st_is_not_wormable;
12754 	} else {
12755 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12756 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12757 		un->un_wormable = st_is_hp_dat_tape_worm;
12758 		wrt = un->un_wormable(un);
12759 	}
12760 
12761 	kmem_free(buf, HP_DAT_INQUIRY);
12762 
12763 	/*
12764 	 * If drive doesn't support it no point in checking further.
12765 	 */
12766 	return (wrt);
12767 }
12768 
12769 static writablity
12770 st_is_hp_lto_tape_worm(struct scsi_tape *un)
12771 {
12772 	writablity wrt;
12773 
12774 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
12775 
12776 	/* Mode sense should be current */
12777 	switch (un->un_mspl->media_type) {
12778 	case 0x00:
12779 		switch (un->un_mspl->density) {
12780 		case 0x40:
12781 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12782 			    "Drive has standard Gen I media loaded\n");
12783 			break;
12784 		case 0x42:
12785 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12786 			    "Drive has standard Gen II media loaded\n");
12787 			break;
12788 		case 0x44:
12789 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12790 			    "Drive has standard Gen III media loaded\n");
12791 			break;
12792 		case 0x46:
12793 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12794 			    "Drive has standard Gen IV media loaded\n");
12795 			break;
12796 		default:
12797 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12798 			    "Drive has standard unknown 0x%X media loaded\n",
12799 			    un->un_mspl->density);
12800 		}
12801 		wrt = RDWR;
12802 		break;
12803 	case 0x01:
12804 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12805 		    "Drive has WORM medium loaded\n");
12806 		wrt = WORM;
12807 		break;
12808 	case 0x80:
12809 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12810 		    "Drive has CD-ROM emulation medium loaded\n");
12811 		wrt = WORM;
12812 		break;
12813 	default:
12814 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12815 		    "Drive has an unexpected medium type 0x%X loaded\n",
12816 		    un->un_mspl->media_type);
12817 		wrt = RDWR;
12818 	}
12819 
12820 	return (wrt);
12821 }
12822 
12823 #define	LTO_REQ_INQUIRY 44
12824 static writablity
12825 st_is_hp_lto_worm(struct scsi_tape *un)
12826 {
12827 	char *buf;
12828 	int result;
12829 	writablity wrt;
12830 
12831 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
12832 
12833 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
12834 
12835 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
12836 
12837 	if (result != 0) {
12838 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12839 		    "Read Standard Inquiry for WORM support failed");
12840 		wrt = FAILED;
12841 	} else if ((buf[40] & 1) == 0) {
12842 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12843 		    "Drive is NOT WORMable\n");
12844 		/* This drive doesn't support it so don't check again */
12845 		un->un_dp->options &= ~ST_WORMABLE;
12846 		wrt = RDWR;
12847 		un->un_wormable = st_is_not_wormable;
12848 	} else {
12849 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12850 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12851 		un->un_wormable = st_is_hp_lto_tape_worm;
12852 		wrt = un->un_wormable(un);
12853 	}
12854 
12855 	kmem_free(buf, LTO_REQ_INQUIRY);
12856 
12857 	/*
12858 	 * If drive doesn't support it no point in checking further.
12859 	 */
12860 	return (wrt);
12861 }
12862 
12863 static writablity
12864 st_is_t10_worm_device(struct scsi_tape *un)
12865 {
12866 	writablity wrt;
12867 
12868 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
12869 
12870 	if (un->un_mspl->media_type == 0x3c) {
12871 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12872 		    "Drive has WORM media loaded\n");
12873 		wrt = WORM;
12874 	} else {
12875 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12876 		    "Drive has non WORM media loaded\n");
12877 		wrt = RDWR;
12878 	}
12879 	return (wrt);
12880 }
12881 
12882 #define	SEQ_CAP_PAGE	(char)0xb0
12883 static writablity
12884 st_is_t10_worm(struct scsi_tape *un)
12885 {
12886 	char *buf;
12887 	int result;
12888 	writablity wrt;
12889 
12890 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
12891 
12892 	buf = kmem_zalloc(6, KM_SLEEP);
12893 
12894 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
12895 
12896 	if (result != 0) {
12897 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12898 		    "Read Vitial Inquiry for Sequental Capability"
12899 		    " WORM support failed %x", result);
12900 		wrt = FAILED;
12901 	} else if ((buf[4] & 1) == 0) {
12902 		ASSERT(buf[1] == SEQ_CAP_PAGE);
12903 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12904 		    "Drive is NOT WORMable\n");
12905 		/* This drive doesn't support it so don't check again */
12906 		un->un_dp->options &= ~ST_WORMABLE;
12907 		wrt = RDWR;
12908 		un->un_wormable = st_is_not_wormable;
12909 	} else {
12910 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12911 		    "Drive supports WORM\n");
12912 		un->un_wormable = st_is_t10_worm_device;
12913 		wrt = un->un_wormable(un);
12914 	}
12915 
12916 	kmem_free(buf, 6);
12917 
12918 	return (wrt);
12919 }
12920 
12921 
12922 #define	STK_REQ_SENSE 26
12923 
12924 static writablity
12925 st_is_stk_worm(struct scsi_tape *un)
12926 {
12927 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
12928 	struct scsi_extended_sense *sense;
12929 	struct uscsi_cmd *cmd;
12930 	char *buf;
12931 	int result;
12932 	writablity wrt;
12933 
12934 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
12935 
12936 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12937 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
12938 	sense = (struct scsi_extended_sense *)buf;
12939 
12940 	cmd->uscsi_flags = USCSI_READ;
12941 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12942 	cmd->uscsi_cdb = &cdb[0];
12943 	cmd->uscsi_bufaddr = buf;
12944 	cmd->uscsi_buflen = STK_REQ_SENSE;
12945 	cmd->uscsi_cdblen = CDB_GROUP0;
12946 	cmd->uscsi_rqlen = 0;
12947 	cmd->uscsi_rqbuf = NULL;
12948 
12949 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12950 
12951 	if (result != 0 || cmd->uscsi_status != 0) {
12952 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12953 		    "Request Sense for WORM failed");
12954 		wrt = RDWR;
12955 	} else if (sense->es_add_len + 8 < 24) {
12956 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12957 		    "Drive didn't send enough sense data for WORM byte %d\n",
12958 		    sense->es_add_len + 8);
12959 		wrt = RDWR;
12960 		un->un_wormable = st_is_not_wormable;
12961 	} else if ((buf[24]) & 0x02) {
12962 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12963 		    "Drive has WORM tape loaded\n");
12964 		wrt = WORM;
12965 		un->un_wormable = st_is_stk_worm;
12966 	} else {
12967 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12968 		    "Drive has normal tape loaded\n");
12969 		wrt = RDWR;
12970 		un->un_wormable = st_is_stk_worm;
12971 	}
12972 
12973 	kmem_free(buf, STK_REQ_SENSE);
12974 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12975 	return (wrt);
12976 }
12977 
12978 #define	DLT_INQ_SZ 44
12979 
12980 static writablity
12981 st_is_dlt_tape_worm(struct scsi_tape *un)
12982 {
12983 	caddr_t buf;
12984 	int result;
12985 	writablity wrt;
12986 
12987 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
12988 
12989 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12990 
12991 	/* Read Attribute Media Type */
12992 
12993 	result = st_read_attributes(un, 0x0408, buf, 10);
12994 
12995 	/*
12996 	 * If this quantum drive is attached via an HBA that cannot
12997 	 * support thr read attributes command return error in the
12998 	 * hope that someday they will support the t10 method.
12999 	 */
13000 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
13001 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13002 		    "Read Attribute Command for WORM Media detection is not "
13003 		    "supported on the HBA that this drive is attached to.");
13004 		wrt = RDWR;
13005 		un->un_wormable = st_is_not_wormable;
13006 		goto out;
13007 	}
13008 
13009 	if (result != 0) {
13010 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13011 		    "Read Attribute Command for WORM Media returned 0x%x",
13012 		    result);
13013 		wrt = RDWR;
13014 		un->un_dp->options &= ~ST_WORMABLE;
13015 		goto out;
13016 	}
13017 
13018 	if ((uchar_t)buf[9] == 0x80) {
13019 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13020 		    "Drive media is WORM\n");
13021 		wrt = WORM;
13022 	} else {
13023 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13024 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
13025 		wrt = RDWR;
13026 	}
13027 
13028 out:
13029 	kmem_free(buf, DLT_INQ_SZ);
13030 	return (wrt);
13031 }
13032 
13033 static writablity
13034 st_is_dlt_worm(struct scsi_tape *un)
13035 {
13036 	caddr_t buf;
13037 	int result;
13038 	writablity wrt;
13039 
13040 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
13041 
13042 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13043 
13044 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
13045 
13046 	if (result != 0) {
13047 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13048 		    "Read Vendor Specific Inquiry for WORM support failed");
13049 		wrt = RDWR;
13050 		goto out;
13051 	}
13052 
13053 	if ((buf[2] & 1) == 0) {
13054 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13055 		    "Drive is not WORMable\n");
13056 		wrt = RDWR;
13057 		un->un_dp->options &= ~ST_WORMABLE;
13058 		un->un_wormable = st_is_not_wormable;
13059 		goto out;
13060 	} else {
13061 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13062 		    "Drive is WORMable\n");
13063 		un->un_wormable = st_is_dlt_tape_worm;
13064 		wrt = un->un_wormable(un);
13065 	}
13066 out:
13067 	kmem_free(buf, DLT_INQ_SZ);
13068 
13069 	return (wrt);
13070 }
13071 
13072 typedef struct {
13073 	struct modeheader_seq header;
13074 #if defined(_BIT_FIELDS_LTOH) /* X86 */
13075 	uchar_t pagecode	:6,
13076 				:2;
13077 	uchar_t page_len;
13078 	uchar_t syslogalive	:2,
13079 		device		:1,
13080 		abs		:1,
13081 		ulpbot		:1,
13082 		prth		:1,
13083 		ponej		:1,
13084 		ait		:1;
13085 	uchar_t span;
13086 
13087 	uchar_t			:6,
13088 		worm		:1,
13089 		mic		:1;
13090 	uchar_t worm_cap	:1,
13091 				:7;
13092 	uint32_t		:32;
13093 #else /* SPARC */
13094 	uchar_t			:2,
13095 		pagecode	:6;
13096 	uchar_t page_len;
13097 	uchar_t ait		:1,
13098 		device		:1,
13099 		abs		:1,
13100 		ulpbot		:1,
13101 		prth		:1,
13102 		ponej		:1,
13103 		syslogalive	:2;
13104 	uchar_t span;
13105 	uchar_t mic		:1,
13106 		worm		:1,
13107 				:6;
13108 	uchar_t			:7,
13109 		worm_cap	:1;
13110 	uint32_t		:32;
13111 #endif
13112 }ait_dev_con;
13113 
13114 #define	AIT_DEV_PAGE 0x31
13115 static writablity
13116 st_is_sony_worm(struct scsi_tape *un)
13117 {
13118 	int result;
13119 	writablity wrt;
13120 	ait_dev_con *ait_conf;
13121 
13122 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13123 
13124 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
13125 
13126 	result = st_gen_mode_sense(un, AIT_DEV_PAGE,
13127 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
13128 
13129 	if (result == 0) {
13130 
13131 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
13132 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13133 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
13134 			    ait_conf->pagecode, AIT_DEV_PAGE);
13135 			wrt = RDWR;
13136 			un->un_wormable = st_is_not_wormable;
13137 
13138 		} else if (ait_conf->worm_cap) {
13139 
13140 			un->un_wormable = st_is_sony_worm;
13141 
13142 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13143 			    "Drives is WORMable\n");
13144 			if (ait_conf->worm) {
13145 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13146 				    "Media is WORM\n");
13147 				wrt = WORM;
13148 			} else {
13149 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13150 				    "Media is not WORM\n");
13151 				wrt = RDWR;
13152 			}
13153 
13154 		} else {
13155 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13156 			    "Drives not is WORMable\n");
13157 			wrt = RDWR;
13158 			/* No further checking required */
13159 			un->un_dp->options &= ~ST_WORMABLE;
13160 		}
13161 
13162 	} else {
13163 
13164 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13165 		    "AIT device config mode sense page read command failed"
13166 		    " result = %d ", result);
13167 		wrt = FAILED;
13168 		un->un_wormable = st_is_not_wormable;
13169 	}
13170 
13171 	kmem_free(ait_conf, sizeof (ait_dev_con));
13172 	return (wrt);
13173 }
13174 
13175 static writablity
13176 st_is_drive_worm(struct scsi_tape *un)
13177 {
13178 	writablity wrt;
13179 
13180 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13181 
13182 	switch (un->un_dp->type) {
13183 	case MT_ISDLT:
13184 		wrt = st_is_dlt_worm(un);
13185 		break;
13186 
13187 	case MT_ISSTK9840:
13188 		wrt = st_is_stk_worm(un);
13189 		break;
13190 
13191 	case MT_IS8MM:
13192 	case MT_ISAIT:
13193 		wrt = st_is_sony_worm(un);
13194 		break;
13195 
13196 	case MT_LTO:
13197 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13198 			wrt = st_is_hp_lto_worm(un);
13199 		} else {
13200 			wrt = st_is_t10_worm(un);
13201 		}
13202 		break;
13203 
13204 	case MT_ISDAT:
13205 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13206 			wrt = st_is_hp_dat_worm(un);
13207 		} else {
13208 			wrt = st_is_t10_worm(un);
13209 		}
13210 		break;
13211 
13212 	default:
13213 		wrt = FAILED;
13214 		break;
13215 	}
13216 
13217 	/*
13218 	 * If any of the above failed try the t10 standard method.
13219 	 */
13220 	if (wrt == FAILED) {
13221 		wrt = st_is_t10_worm(un);
13222 	}
13223 
13224 	/*
13225 	 * Unknown method for detecting WORM media.
13226 	 */
13227 	if (wrt == FAILED) {
13228 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13229 		    "Unknown method for WORM media detection\n");
13230 		wrt = RDWR;
13231 		un->un_dp->options &= ~ST_WORMABLE;
13232 	}
13233 
13234 	return (wrt);
13235 }
13236 
13237 static int
13238 st_read_attributes(struct scsi_tape *un, uint16_t attribute, caddr_t buf,
13239     size_t size)
13240 {
13241 	char cdb[CDB_GROUP4];
13242 	int result;
13243 	struct uscsi_cmd *cmd;
13244 
13245 	ST_FUNC(ST_DEVINFO, st_read_attributes);
13246 
13247 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13248 
13249 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
13250 	cdb[1] = 0;
13251 	cdb[2] = 0;
13252 	cdb[3] = 0;
13253 	cdb[4] = 0;
13254 	cdb[5] = 0;
13255 	cdb[6] = 0;
13256 	cdb[7] = 0;
13257 	cdb[8] = (char)(attribute >> 8);
13258 	cdb[9] = (char)(attribute);
13259 	cdb[10] = (char)(size >> 24);
13260 	cdb[11] = (char)(size >> 16);
13261 	cdb[12] = (char)(size >> 8);
13262 	cdb[13] = (char)(size);
13263 	cdb[14] = 0;
13264 	cdb[15] = 0;
13265 
13266 
13267 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
13268 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13269 	cmd->uscsi_cdb = &cdb[0];
13270 	cmd->uscsi_bufaddr = (caddr_t)buf;
13271 	cmd->uscsi_buflen = size;
13272 	cmd->uscsi_cdblen = sizeof (cdb);
13273 
13274 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13275 
13276 	if (result != 0 || cmd->uscsi_status != 0) {
13277 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13278 		    "st_read_attribute failed: result %d status %d\n",
13279 		    result, cmd->uscsi_status);
13280 		if (result == 0) {
13281 			result = EIO;
13282 		}
13283 		goto exit;
13284 	}
13285 
13286 	/*
13287 	 * The attribute retured should match the attribute requested.
13288 	 */
13289 	if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
13290 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13291 		    "bad? data", buf, size);
13292 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13293 		    "st_read_attribute got wrong data back expected 0x%x"
13294 		    " got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
13295 		result = EIO;
13296 	}
13297 exit:
13298 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13299 
13300 	return (result);
13301 }
13302 
13303 static int
13304 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
13305     uchar_t page)
13306 {
13307 	char cdb[CDB_GROUP0];
13308 	struct scsi_extended_sense *sense;
13309 	struct uscsi_cmd *cmd;
13310 	int result;
13311 
13312 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
13313 
13314 	cdb[0] = SCMD_INQUIRY;
13315 	cdb[1] = page ? 1 : 0;
13316 	cdb[2] = page;
13317 	cdb[3] = 0;
13318 	cdb[4] = size;
13319 	cdb[5] = 0;
13320 
13321 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13322 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
13323 
13324 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
13325 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13326 	cmd->uscsi_cdb = &cdb[0];
13327 	cmd->uscsi_bufaddr = dest;
13328 	cmd->uscsi_buflen = size;
13329 	cmd->uscsi_cdblen = CDB_GROUP0;
13330 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
13331 	cmd->uscsi_rqbuf = (caddr_t)sense;
13332 
13333 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13334 
13335 	if (result != 0 || cmd->uscsi_status != 0) {
13336 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13337 		    "st_get_special_inquiry() failed for page %x", page);
13338 		if (result == 0) {
13339 			result = EIO;
13340 		}
13341 	}
13342 
13343 	kmem_free(sense, sizeof (struct scsi_extended_sense));
13344 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13345 
13346 	return (result);
13347 }
13348 
13349 
13350 static int
13351 st_update_block_pos(struct scsi_tape *un)
13352 {
13353 	int rval = ENOTTY;
13354 
13355 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
13356 
13357 	while (un->un_read_pos_type != NO_POS) {
13358 		rval = st_cmd(un->un_dev, SCMD_READ_POSITION, 32, SYNC_CMD);
13359 
13360 		if (rval == 0) {
13361 			rval = st_interpret_read_pos(un, un->un_read_pos_type,
13362 			    32, (caddr_t)un->un_read_pos_data);
13363 			break;
13364 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
13365 			continue;
13366 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
13367 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13368 			    "st_update_block_pos() read position cmd %x"
13369 			    " returned %x un_status = %d",
13370 			    un->un_read_pos_type, rval, un->un_status);
13371 			break;
13372 		} else {
13373 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
13374 			    "st_update_block_pos() read position cmd %x"
13375 			    " returned %x", un->un_read_pos_type, rval);
13376 		}
13377 
13378 		switch (un->un_read_pos_type) {
13379 		case SHORT_POS:
13380 			un->un_read_pos_type = NO_POS;
13381 			break;
13382 
13383 		case LONG_POS:
13384 			un->un_read_pos_type = EXT_POS;
13385 			break;
13386 
13387 		case EXT_POS:
13388 			un->un_read_pos_type = SHORT_POS;
13389 			break;
13390 
13391 		default:
13392 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13393 			    "Unexpected read position type 0x%x",
13394 			    un->un_read_pos_type);
13395 		}
13396 	}
13397 
13398 	return (rval);
13399 }
13400 
13401 static int
13402 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
13403 {
13404 	int result;
13405 	size_t d_sz;
13406 	caddr_t pos_info;
13407 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
13408 
13409 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
13410 
13411 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
13412 		return (0);
13413 	}
13414 
13415 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
13416 
13417 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13418 		    "bp_mapin_common() failed");
13419 
13420 		return (EIO);
13421 	}
13422 
13423 	pos_info = bp->b_un.b_addr;
13424 	d_sz = bp->b_bcount - bp->b_resid;
13425 
13426 #ifdef DEBUG
13427 	if ((st_debug & 0xf) > 2) {
13428 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13429 		    "st_get_read_pos() position info",
13430 		    pos_info, bp->b_bcount);
13431 	}
13432 #endif
13433 
13434 	result = st_interpret_read_pos(un, cmd->uscsi_cdb[1], d_sz, pos_info);
13435 
13436 	bp_mapout(bp);
13437 
13438 	return (result);
13439 }
13440 
13441 #if defined(_BIG_ENDIAN)
13442 
13443 #define	FIX_ENDIAN32(x)
13444 #define	FIX_ENDIAN64(x)
13445 
13446 #elif defined(_LITTLE_ENDIAN)
13447 
13448 static void
13449 st_swap32(uint32_t *val)
13450 {
13451 	uint32_t tmp;
13452 
13453 	tmp =  (*val >> 24) & 0xff;
13454 	tmp |= (*val >>  8) & 0xff00;
13455 	tmp |= (*val <<  8) & 0xff0000;
13456 	tmp |= (*val << 24) & 0xff000000;
13457 
13458 	*val = tmp;
13459 }
13460 
13461 static void
13462 st_swap64(uint64_t *val)
13463 {
13464 	uint32_t low;
13465 	uint32_t high;
13466 
13467 	low =  (uint32_t)(*val);
13468 	high = (uint32_t)(*val >> 32);
13469 
13470 	st_swap32(&low);
13471 	st_swap32(&high);
13472 
13473 	*val =  high;
13474 	*val |= ((uint64_t)low << 32);
13475 }
13476 
13477 #define	FIX_ENDIAN32(x) st_swap32(x)
13478 #define	FIX_ENDIAN64(x) st_swap64(x)
13479 #endif
13480 
13481 static int
13482 st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
13483     size_t data_sz, caddr_t responce)
13484 {
13485 	int rval = 0;
13486 
13487 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
13488 
13489 	/*
13490 	 * Look at byte 1 of cdb to see what kind of read position
13491 	 * was requested.
13492 	 */
13493 	switch (type) {
13494 
13495 	case SHORT_POS: /* Short data format */
13496 	{
13497 		tape_position_t *pos_info = (tape_position_t *)responce;
13498 		uint32_t value;
13499 
13500 		/* If reserved fields are non zero don't use the data */
13501 		if (pos_info->reserved0 || pos_info->reserved1 ||
13502 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
13503 		    pos_info->reserved3) {
13504 			rval = EIO;
13505 			break;
13506 		}
13507 		/*
13508 		 * Position is to large to use this type of read position.
13509 		 */
13510 		if (pos_info->posi_err == 1) {
13511 			rval = ERANGE;
13512 			break;
13513 		}
13514 
13515 		if (pos_info->blk_posi_unkwn == 0) {
13516 
13517 			if (un->un_pos.partition !=
13518 			    pos_info->partition_number) {
13519 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13520 				    "SHORT_POS current partition %d read %d\n",
13521 				    un->un_pos.partition,
13522 				    pos_info->partition_number);
13523 			}
13524 			un->un_pos.partition = pos_info->partition_number;
13525 			value = pos_info->host_block;
13526 			FIX_ENDIAN32(&value);
13527 
13528 			if (un->un_pos.lgclblkno != value) {
13529 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13530 				    "SHORT_POS current logical 0x%"PRIx64" read"
13531 				    " 0x%x\n", un->un_pos.lgclblkno, value);
13532 			}
13533 
13534 			un->un_pos.lgclblkno = (uint64_t)value;
13535 
13536 			if (pos_info->begin_of_part && pos_info->end_of_part) {
13537 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
13538 				    "SHORT_POS returned begin and end of"
13539 				    " partition\n");
13540 				break;
13541 			}
13542 			/* Is drive rewound */
13543 			if ((pos_info->begin_of_part == 1) &&
13544 			    (pos_info->host_block == 0)) {
13545 				un->un_pos.blkno = 0;
13546 				un->un_pos.fileno = 0;
13547 				un->un_pos.pmode = legacy;
13548 			} else if (un->un_pos.pmode == invalid) {
13549 				/* If we were lost now were found */
13550 				un->un_pos.pmode = logical;
13551 			}
13552 		} else {
13553 			un->un_pos.pmode = invalid;
13554 		}
13555 		break;
13556 	}
13557 
13558 	case LONG_POS: /* Long data format */
13559 	{
13560 		uint64_t value;
13561 		tape_position_long_t *long_pos_info =
13562 		    (tape_position_long_t *)responce;
13563 
13564 		/* If reserved fields are non zero don't use the data */
13565 		if ((long_pos_info->reserved0) ||
13566 		    (long_pos_info->reserved1) ||
13567 		    (long_pos_info->reserved2)) {
13568 			rval = EIO;
13569 			break;
13570 		}
13571 
13572 		/* Is position Valid */
13573 		if (long_pos_info->blk_posi_unkwn == 0) {
13574 			uint32_t part;
13575 
13576 			part = long_pos_info->partition;
13577 			FIX_ENDIAN32(&part);
13578 			if (un->un_pos.partition != part) {
13579 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13580 				    "LONG_POS current partition %d"
13581 				    " read %d\n", un->un_pos.partition, part);
13582 			}
13583 			un->un_pos.partition = part;
13584 			value = long_pos_info->block_number;
13585 			FIX_ENDIAN64(&value);
13586 			if (un->un_pos.lgclblkno != value) {
13587 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13588 				    "LONG_POS current logical 0x%"PRIx64
13589 				    " read 0x%"PRIx64"\n",
13590 				    un->un_pos.lgclblkno, value);
13591 			}
13592 			un->un_pos.lgclblkno = value;
13593 
13594 			if (long_pos_info->begin_of_part &&
13595 			    long_pos_info->end_of_part) {
13596 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
13597 				    "LONG_POS returned begin and end of"
13598 				    " partition\n");
13599 				break;
13600 			}
13601 			if ((long_pos_info->begin_of_part == 1) &&
13602 			    (long_pos_info->block_number == 0)) {
13603 				un->un_pos.blkno = 0;
13604 				un->un_pos.fileno = 0;
13605 				un->un_pos.pmode = legacy;
13606 			} else if (un->un_pos.pmode == invalid) {
13607 				un->un_pos.pmode = logical;
13608 			}
13609 		} else {
13610 			/*
13611 			 * If the drive doesn't know location,
13612 			 * we don't either.
13613 			 */
13614 			un->un_pos.pmode = invalid;
13615 		}
13616 
13617 		value = long_pos_info->file_number;
13618 		FIX_ENDIAN64(&value);
13619 		/* Is file position valid */
13620 		if (long_pos_info->mrk_posi_unkwn == 0) {
13621 			if (((un->un_pos.pmode == legacy) ||
13622 			    (un->un_pos.pmode == logical)) &&
13623 			    (un->un_pos.fileno != value)) {
13624 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13625 				    "LONG_POS fileno 0x%"PRIx64
13626 				    " not un_pos %x\n", value,
13627 				    un->un_pos.fileno);
13628 			} else if (un->un_pos.pmode == invalid) {
13629 				un->un_pos.pmode = logical;
13630 			}
13631 			un->un_pos.fileno = (int32_t)value;
13632 		} else {
13633 			/*
13634 			 * If the drive doesn't know its position,
13635 			 * we don't either.
13636 			 */
13637 			un->un_pos.pmode = invalid;
13638 		}
13639 		if (un->un_pos.pmode != invalid && long_pos_info->end_of_part) {
13640 			un->un_pos.eof = ST_EOT;
13641 		}
13642 
13643 		break;
13644 	}
13645 
13646 	case EXT_POS: /* Extended data format */
13647 	{
13648 		uint64_t value;
13649 		tape_position_ext_t *ext_pos_info =
13650 		    (tape_position_ext_t *)responce;
13651 
13652 		/* Make sure that there is enough data there */
13653 		if (data_sz < 16) {
13654 			break;
13655 		}
13656 
13657 		/* If reserved fields are non zero don't use the data */
13658 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
13659 			rval = EIO;
13660 			break;
13661 		}
13662 
13663 		/*
13664 		 * In the unlikely event of overflowing 64 bits of position.
13665 		 */
13666 		if (ext_pos_info->posi_err != 0) {
13667 			rval = ERANGE;
13668 			break;
13669 		}
13670 
13671 		/* Is block position information valid */
13672 		if (ext_pos_info->blk_posi_unkwn == 0) {
13673 
13674 			if (un->un_pos.partition != ext_pos_info->partition) {
13675 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13676 				    "EXT_POS current partition %d read %d\n",
13677 				    un->un_pos.partition,
13678 				    ext_pos_info->partition);
13679 			}
13680 			un->un_pos.partition = ext_pos_info->partition;
13681 
13682 			value = ext_pos_info->host_block;
13683 			FIX_ENDIAN64(&value);
13684 			if (un->un_pos.lgclblkno != value) {
13685 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13686 				    "EXT_POS current logical 0x%"PRIx64
13687 				    " read 0x%"PRIx64"\n",
13688 				    un->un_pos.lgclblkno, value);
13689 			}
13690 			un->un_pos.lgclblkno = value;
13691 			if ((ext_pos_info->begin_of_part == 1) &&
13692 			    (ext_pos_info->host_block == 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 			un->un_pos.pmode = invalid;
13701 		}
13702 		break;
13703 	}
13704 
13705 	default:
13706 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13707 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
13708 		rval = EIO;
13709 	}
13710 
13711 	return (rval);
13712 }
13713 
13714 static int
13715 st_logical_block_locate(struct scsi_tape *un, uint64_t lblk, uchar_t partition)
13716 {
13717 	int rval;
13718 	char cdb[CDB_GROUP4];
13719 	struct uscsi_cmd *cmd;
13720 	struct scsi_extended_sense sense;
13721 
13722 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
13723 
13724 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13725 
13726 	if (lblk <= INT32_MAX) {
13727 		cmd->uscsi_cdblen = CDB_GROUP1;
13728 		cdb[0] = SCMD_LOCATE;
13729 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13730 		cdb[2] = 0;
13731 		cdb[3] = (char)(lblk >> 24);
13732 		cdb[4] = (char)(lblk >> 16);
13733 		cdb[5] = (char)(lblk >> 8);
13734 		cdb[6] = (char)(lblk);
13735 		cdb[7] = 0;
13736 		cdb[8] = partition;
13737 		cdb[9] = 0;
13738 	} else {
13739 		/*
13740 		 * If the drive doesn't give a 64 bit read position data
13741 		 * it is unlikely it will accept 64 bit locates.
13742 		 */
13743 		if (un->un_read_pos_type != LONG_POS) {
13744 			kmem_free(cmd, sizeof (struct uscsi_cmd));
13745 			return (ERANGE);
13746 		}
13747 		cmd->uscsi_cdblen = CDB_GROUP4;
13748 		cdb[0] = (char)SCMD_LOCATE_G4;
13749 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13750 		cdb[2] = 0;
13751 		cdb[3] = partition;
13752 		cdb[4] = (char)(lblk >> 56);
13753 		cdb[5] = (char)(lblk >> 48);
13754 		cdb[6] = (char)(lblk >> 40);
13755 		cdb[7] = (char)(lblk >> 32);
13756 		cdb[8] = (char)(lblk >> 24);
13757 		cdb[9] = (char)(lblk >> 16);
13758 		cdb[10] = (char)(lblk >> 8);
13759 		cdb[11] = (char)(lblk);
13760 		cdb[12] = 0;
13761 		cdb[13] = 0;
13762 		cdb[14] = 0;
13763 		cdb[15] = 0;
13764 	}
13765 
13766 
13767 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
13768 	cmd->uscsi_rqbuf = (caddr_t)&sense;
13769 	cmd->uscsi_rqlen = sizeof (sense);
13770 	cmd->uscsi_timeout = un->un_dp->space_timeout;
13771 	cmd->uscsi_cdb = cdb;
13772 
13773 	rval = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13774 
13775 	un->un_pos.pmode = logical;
13776 	un->un_pos.eof = ST_NO_EOF;
13777 
13778 	if (lblk > INT32_MAX) {
13779 		/*
13780 		 * XXX This is a work around till we handle Descriptor format
13781 		 * sense data. Since we are sending a command where the standard
13782 		 * sense data can not correctly represent a correct residual in
13783 		 * 4 bytes.
13784 		 */
13785 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13786 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13787 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
13788 			/* Doesn't like big locate command */
13789 			un->un_status = 0;
13790 			rval = ERANGE;
13791 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
13792 			/* Aborted big locate command */
13793 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13794 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
13795 			    rval);
13796 			un->un_status = 0;
13797 			rval = EIO;
13798 		} else if (st_update_block_pos(un)) {
13799 			/* read position failed */
13800 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13801 			    "Big LOCATE and read pos: rval = %d\n", rval);
13802 			rval = EIO;
13803 		} else if (lblk > un->un_pos.lgclblkno) {
13804 			/* read position worked but position was not expected */
13805 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13806 			    "Big LOCATE and recover read less then desired 0x%"
13807 			    PRIx64"\n", un->un_pos.lgclblkno);
13808 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
13809 			un->un_status = KEY_BLANK_CHECK;
13810 			rval = ESPIPE;
13811 		} else if (lblk == un->un_pos.lgclblkno) {
13812 			/* read position was what was expected */
13813 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13814 			    "Big LOCATE and recover seems to have worked\n");
13815 			un->un_err_resid = 0;
13816 			rval = 0;
13817 		} else {
13818 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13819 			    "BIGLOCATE end up going backwards");
13820 			un->un_err_resid = lblk;
13821 			rval = EIO;
13822 		}
13823 
13824 	} else if (rval == 0) {
13825 		/* Worked as requested */
13826 		un->un_pos.lgclblkno = lblk;
13827 
13828 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
13829 	    (cmd->uscsi_resid != 0)) {
13830 		/* Got part way there but wasn't enough blocks on tape */
13831 		un->un_pos.lgclblkno = lblk - cmd->uscsi_resid;
13832 		un->un_err_resid = cmd->uscsi_resid;
13833 		un->un_status = KEY_BLANK_CHECK;
13834 		rval = ESPIPE;
13835 
13836 	} else if (st_update_block_pos(un) == 0) {
13837 		/* Got part way there but drive didn't tell what we missed by */
13838 		un->un_err_resid = lblk - un->un_pos.lgclblkno;
13839 		un->un_status = KEY_BLANK_CHECK;
13840 		rval = ESPIPE;
13841 
13842 	} else {
13843 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13844 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
13845 		    rval, cmd->uscsi_status);
13846 		un->un_err_resid = lblk;
13847 		un->un_status = KEY_ILLEGAL_REQUEST;
13848 		un->un_pos.pmode = invalid;
13849 		rval = EIO;
13850 	}
13851 
13852 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13853 
13854 	return (rval);
13855 }
13856 
13857 static int
13858 st_mtfsf_ioctl(struct scsi_tape *un, int files)
13859 {
13860 	int rval;
13861 
13862 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
13863 
13864 
13865 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13866 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13867 
13868 	/* pmode == invalid already handled */
13869 	if (un->un_pos.pmode == legacy) {
13870 		/*
13871 		 * forward space over filemark
13872 		 *
13873 		 * For ASF we allow a count of 0 on fsf which means
13874 		 * we just want to go to beginning of current file.
13875 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
13876 		 * Allow stepping over double fmk with reel
13877 		 */
13878 		if ((un->un_pos.eof >= ST_EOT) &&
13879 		    (files > 0) &&
13880 		    ((un->un_dp->options & ST_REEL) == 0)) {
13881 			/* we're at EOM */
13882 			un->un_err_resid = files;
13883 			un->un_status = KEY_BLANK_CHECK;
13884 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13885 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
13886 			return (EIO);
13887 		}
13888 
13889 		/*
13890 		 * physical tape position may not be what we've been
13891 		 * telling the user; adjust the request accordingly
13892 		 */
13893 		if (IN_EOF(un->un_pos)) {
13894 			un->un_pos.fileno++;
13895 			un->un_pos.blkno = 0;
13896 			/*
13897 			 * For positive direction case, we're now covered.
13898 			 * For zero or negative direction, we're covered
13899 			 * (almost)
13900 			 */
13901 			files--;
13902 		}
13903 
13904 	}
13905 
13906 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13907 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13908 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
13909 		return (EIO);
13910 	}
13911 
13912 
13913 	/*
13914 	 * Forward space file marks.
13915 	 * We leave ourselves at block zero
13916 	 * of the target file number.
13917 	 */
13918 	if (files < 0) {
13919 		rval = st_backward_space_files(un, -files, 0);
13920 	} else {
13921 		rval = st_forward_space_files(un, files);
13922 	}
13923 
13924 	return (rval);
13925 }
13926 
13927 static int
13928 st_forward_space_files(struct scsi_tape *un, int count)
13929 {
13930 	dev_t dev;
13931 	int rval;
13932 
13933 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
13934 
13935 	dev = un->un_dev;
13936 
13937 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13938 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
13939 
13940 	ASSERT(count >= 0);
13941 	ASSERT(un->un_pos.pmode != invalid);
13942 
13943 	/*
13944 	 * A space with a count of zero means take me to the start of file.
13945 	 */
13946 	if (count == 0) {
13947 
13948 		/* Hay look were already there */
13949 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0 &&
13950 		    un->un_pos.fileno == 0) {
13951 			un->un_err_resid = 0;
13952 			COPY_POS(&un->un_err_pos, &un->un_pos);
13953 			return (0);
13954 		}
13955 
13956 		/*
13957 		 * Well we are in the first file.
13958 		 * A rewind will get to the start.
13959 		 */
13960 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
13961 			rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
13962 
13963 		/*
13964 		 * Can we backspace to get there?
13965 		 * This should work in logical mode.
13966 		 */
13967 		} else if (un->un_dp->options & ST_BSF) {
13968 			rval = st_space_to_begining_of_file(un);
13969 
13970 		/*
13971 		 * Can't back space but current file number is known,
13972 		 * So rewind and space from the begining of the partition.
13973 		 */
13974 		} else if (un->un_pos.pmode == legacy) {
13975 			rval = st_scenic_route_to_begining_of_file(un,
13976 			    un->un_pos.fileno);
13977 
13978 		/*
13979 		 * pmode is logical and ST_BSF is not set.
13980 		 * The LONG_POS read position contains the fileno.
13981 		 * If the read position works, rewind and space.
13982 		 */
13983 		} else if (un->un_read_pos_type == LONG_POS) {
13984 			rval = st_cmd(dev, SCMD_READ_POSITION, 0, SYNC_CMD);
13985 			if (rval) {
13986 				/*
13987 				 * We didn't get the file position from the
13988 				 * read position command.
13989 				 * We are going to trust the drive to backspace
13990 				 * and then position after the filemark.
13991 				 */
13992 				rval = st_space_to_begining_of_file(un);
13993 			}
13994 			rval = st_interpret_read_pos(un, LONG_POS, 32,
13995 			    (caddr_t)un->un_read_pos_data);
13996 			if ((rval) && (un->un_pos.pmode == invalid)) {
13997 				rval = st_space_to_begining_of_file(un);
13998 			} else {
13999 				rval = st_scenic_route_to_begining_of_file(un,
14000 				    un->un_pos.fileno);
14001 			}
14002 		} else {
14003 			rval = EIO;
14004 		}
14005 		/*
14006 		 * If something didn't work we are lost
14007 		 */
14008 		if (rval != 0) {
14009 			un->un_pos.pmode = invalid;
14010 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14011 			    "st_mtioctop : EIO : fspace pmode invalid");
14012 
14013 			rval = EIO;
14014 		}
14015 
14016 	} else {
14017 		rval = st_space_fmks(dev, count);
14018 	}
14019 
14020 	if (rval != EIO && count < 0) {
14021 		/*
14022 		 * we came here with a count < 0; we now need
14023 		 * to skip back to end up before the filemark
14024 		 */
14025 		rval = st_backward_space_files(un, 1, 1);
14026 	}
14027 
14028 	return (rval);
14029 }
14030 
14031 static int
14032 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
14033 {
14034 	int rval;
14035 
14036 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
14037 
14038 	if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
14039 		rval = EIO;
14040 	} else if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
14041 		rval = EIO;
14042 	}
14043 
14044 	return (rval);
14045 }
14046 
14047 static int
14048 st_space_to_begining_of_file(struct scsi_tape *un)
14049 {
14050 	int rval;
14051 
14052 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
14053 
14054 	/*
14055 	 * Back space of the file at the begining of the file.
14056 	 */
14057 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD);
14058 	if (rval) {
14059 		rval = EIO;
14060 		return (rval);
14061 	}
14062 
14063 	/*
14064 	 * Other interesting answers might be crashed BOT which isn't bad.
14065 	 */
14066 	if (un->un_status == SUN_KEY_BOT) {
14067 		return (rval);
14068 	}
14069 
14070 	/*
14071 	 * Now we are on the BOP side of the filemark. Forward space to
14072 	 * the EOM side and we are at the begining of the file.
14073 	 */
14074 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD);
14075 	if (rval) {
14076 		rval = EIO;
14077 	}
14078 
14079 	return (rval);
14080 }
14081 
14082 static int
14083 st_mtfsr_ioctl(struct scsi_tape *un, int count)
14084 {
14085 
14086 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
14087 
14088 	/*
14089 	 * forward space to inter-record gap
14090 	 *
14091 	 */
14092 
14093 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14094 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
14095 
14096 	if (un->un_pos.pmode == legacy) {
14097 		/*
14098 		 * If were are at end of tape and count is forward.
14099 		 * Return blank check.
14100 		 */
14101 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
14102 			/* we're at EOM */
14103 			un->un_err_resid = count;
14104 			un->un_status = KEY_BLANK_CHECK;
14105 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14106 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
14107 			return (EIO);
14108 		}
14109 
14110 		/*
14111 		 * If count is zero there is nothing to do.
14112 		 */
14113 		if (count == 0) {
14114 			un->un_err_pos.fileno = un->un_pos.fileno;
14115 			un->un_err_pos.blkno = un->un_pos.blkno;
14116 			un->un_err_resid = 0;
14117 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14118 				un->un_status = SUN_KEY_EOF;
14119 			}
14120 			return (0);
14121 		}
14122 
14123 		/*
14124 		 * physical tape position may not be what we've been
14125 		 * telling the user; adjust the position accordingly
14126 		 */
14127 		if (IN_EOF(un->un_pos)) {
14128 			daddr_t blkno = un->un_pos.blkno;
14129 			int fileno = un->un_pos.fileno;
14130 
14131 			optype lastop = un->un_lastop;
14132 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
14133 			    == -1) {
14134 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14135 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
14136 				return (EIO);
14137 			}
14138 
14139 			un->un_pos.blkno = blkno;
14140 			un->un_pos.fileno = fileno;
14141 			un->un_lastop = lastop;
14142 		}
14143 	}
14144 
14145 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14146 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14147 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
14148 		return (EIO);
14149 	}
14150 
14151 	return (st_space_records(un, count));
14152 }
14153 
14154 static int
14155 st_space_records(struct scsi_tape *un, int count)
14156 {
14157 	int dblk;
14158 	int rval = 0;
14159 
14160 	ST_FUNC(ST_DEVINFO, st_space_records);
14161 
14162 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14163 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
14164 
14165 	if (un->un_pos.pmode == logical) {
14166 		rval = st_cmd(un->un_dev, SCMD_SPACE, Blk(count), SYNC_CMD);
14167 		if (rval != 0) {
14168 			rval = EIO;
14169 		}
14170 		return (rval);
14171 	}
14172 
14173 	dblk = un->un_pos.blkno + count;
14174 
14175 	/* Already there */
14176 	if (dblk == un->un_pos.blkno) {
14177 		un->un_err_resid = 0;
14178 		COPY_POS(&un->un_err_pos, &un->un_pos);
14179 		return (0);
14180 	}
14181 
14182 	/*
14183 	 * If the destination block is forward
14184 	 * or the drive will backspace records.
14185 	 */
14186 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
14187 		/*
14188 		 * If we're spacing forward, or the device can
14189 		 * backspace records, we can just use the SPACE
14190 		 * command.
14191 		 */
14192 		dblk -= un->un_pos.blkno;
14193 		if (st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
14194 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14195 			    "st_space_records:EIO:space_records can't spc");
14196 			rval = EIO;
14197 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
14198 			/*
14199 			 * check if we hit BOT/EOT
14200 			 */
14201 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
14202 				un->un_status = SUN_KEY_BOT;
14203 				un->un_pos.eof = ST_NO_EOF;
14204 			} else if (dblk < 0 &&
14205 			    un->un_pos.eof == ST_EOF_PENDING) {
14206 				int residue = un->un_err_resid;
14207 				/*
14208 				 * we skipped over a filemark
14209 				 * and need to go forward again
14210 				 */
14211 				if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1),
14212 				    SYNC_CMD)) {
14213 					ST_DEBUG2(ST_DEVINFO, st_label,
14214 					    SCSI_DEBUG, "st_space_records: EIO"
14215 					    " : can't space #2");
14216 					rval = EIO;
14217 				}
14218 				un->un_err_resid = residue;
14219 			}
14220 			if (rval == 0) {
14221 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14222 				    "st_space_records: EIO : space_rec rval"
14223 				    " == 0");
14224 				rval = EIO;
14225 			}
14226 		}
14227 	} else {
14228 		/*
14229 		 * else we rewind, space forward across filemarks to
14230 		 * the desired file, and then space records to the
14231 		 * desired block.
14232 		 */
14233 
14234 		int dfile = un->un_pos.fileno;	/* save current file */
14235 
14236 		if (dblk < 0) {
14237 			/*
14238 			 * Wups - we're backing up over a filemark
14239 			 */
14240 			if (un->un_pos.blkno != 0 &&
14241 			    (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
14242 			    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile),
14243 			    SYNC_CMD))) {
14244 				un->un_pos.pmode = invalid;
14245 			}
14246 			un->un_err_resid = -dblk;
14247 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
14248 				un->un_status = SUN_KEY_BOT;
14249 				un->un_pos.eof = ST_NO_EOF;
14250 			} else if (un->un_pos.fileno > 0) {
14251 				un->un_status = SUN_KEY_EOF;
14252 				un->un_pos.eof = ST_NO_EOF;
14253 			}
14254 			COPY_POS(&un->un_err_pos, &un->un_pos);
14255 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14256 			    "st_space_records:EIO:space_records : dblk < 0");
14257 			rval = EIO;
14258 		} else if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
14259 		    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
14260 		    st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
14261 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14262 			    "st_space_records: EIO :space_records : rewind "
14263 			    "and space failed");
14264 			un->un_pos.pmode = invalid;
14265 			rval = EIO;
14266 		}
14267 	}
14268 
14269 	return (rval);
14270 }
14271 
14272 static int
14273 st_mtbsf_ioctl(struct scsi_tape *un, int files)
14274 {
14275 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
14276 
14277 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14278 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
14279 	/*
14280 	 * backward space of file filemark (1/2" and 8mm)
14281 	 * tape position will end on the beginning of tape side
14282 	 * of the desired file mark
14283 	 */
14284 	if ((un->un_dp->options & ST_BSF) == 0) {
14285 		return (ENOTTY);
14286 	}
14287 
14288 	if (un->un_pos.pmode == legacy) {
14289 
14290 		/*
14291 		 * If a negative count (which implies a forward space op)
14292 		 * is specified, and we're at logical or physical eot,
14293 		 * bounce the request.
14294 		 */
14295 
14296 		if (un->un_pos.eof >= ST_EOT && files < 0) {
14297 			un->un_err_resid = files;
14298 			un->un_status = SUN_KEY_EOT;
14299 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14300 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
14301 			return (EIO);
14302 		}
14303 		/*
14304 		 * physical tape position may not be what we've been
14305 		 * telling the user; adjust the request accordingly
14306 		 */
14307 		if (IN_EOF(un->un_pos)) {
14308 			un->un_pos.fileno++;
14309 			un->un_pos.blkno = 0;
14310 			files++;
14311 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14312 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
14313 			    files, MTBSF);
14314 
14315 		}
14316 	}
14317 
14318 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14319 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14320 		    "st_ioctl : EIO : MTBSF : check den wfm");
14321 		return (EIO);
14322 	}
14323 
14324 	if (files <= 0) {
14325 		/*
14326 		 * for a negative count, we need to step forward
14327 		 * first and then step back again
14328 		 */
14329 		files = -files + 1;
14330 		return (st_forward_space_files(un, files));
14331 	}
14332 	return (st_backward_space_files(un, files, 1));
14333 }
14334 
14335 static int
14336 st_backward_space_files(struct scsi_tape *un, int count, int infront)
14337 {
14338 	int end_fileno;
14339 	int skip_cnt;
14340 	int rval = 0;
14341 
14342 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
14343 
14344 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14345 	    "st_backward_space_files: count=%x eof=%x\n",
14346 	    count, un->un_pos.eof);
14347 	/*
14348 	 * Backspace files (MTNBSF): infront == 0
14349 	 *
14350 	 *	For tapes that can backspace, backspace
14351 	 *	count+1 filemarks and then run forward over
14352 	 *	a filemark
14353 	 *
14354 	 *	For tapes that can't backspace,
14355 	 *		calculate desired filenumber
14356 	 *		(un->un_pos.fileno - count), rewind,
14357 	 *		and then space forward this amount
14358 	 *
14359 	 * Backspace filemarks (MTBSF) infront == 1
14360 	 *
14361 	 *	For tapes that can backspace, backspace count
14362 	 *	filemarks
14363 	 *
14364 	 *	For tapes that can't backspace, calculate
14365 	 *	desired filenumber (un->un_pos.fileno - count),
14366 	 *	add 1, rewind, space forward this amount,
14367 	 *	and mark state as ST_EOF_PENDING appropriately.
14368 	 */
14369 
14370 	if (un->un_pos.pmode == logical) {
14371 
14372 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14373 		    "st_backward_space_files: mt_op=%x count=%x"
14374 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
14375 		    un->un_pos.lgclblkno);
14376 
14377 
14378 		/* In case a drive that won't back space gets in logical mode */
14379 		if ((un->un_dp->options & ST_BSF) == 0) {
14380 			rval = EIO;
14381 			return (rval);
14382 		}
14383 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
14384 			rval = EIO;
14385 			return (rval);
14386 		}
14387 		if ((infront != 0) &&
14388 		    (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
14389 			rval = EIO;
14390 			return (rval);
14391 		}
14392 		return (rval);
14393 	}
14394 
14395 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14396 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
14397 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
14398 
14399 
14400 
14401 	/*
14402 	 * Handle the simple case of BOT
14403 	 * playing a role in these cmds.
14404 	 * We do this by calculating the
14405 	 * ending file number. If the ending
14406 	 * file is < BOT, rewind and set an
14407 	 * error and mark resid appropriately.
14408 	 * If we're backspacing a file (not a
14409 	 * filemark) and the target file is
14410 	 * the first file on the tape, just
14411 	 * rewind.
14412 	 */
14413 
14414 	/* figure expected destination of this SPACE command */
14415 	end_fileno = un->un_pos.fileno - count;
14416 
14417 	/*
14418 	 * Would the end effect of this SPACE be the same as rewinding?
14419 	 * If so just rewind instead.
14420 	 */
14421 	if ((infront != 0) && (end_fileno < 0) ||
14422 	    (infront == 0) && (end_fileno <= 0)) {
14423 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
14424 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14425 			    "st_backward_space_files: EIO : "
14426 			    "rewind in lou of BSF failed\n");
14427 			rval = EIO;
14428 		}
14429 		if (end_fileno < 0) {
14430 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14431 			    "st_backward_space_files: EIO : "
14432 			    "back space file greater then fileno\n");
14433 			rval = EIO;
14434 			un->un_err_resid = -end_fileno;
14435 			un->un_status = SUN_KEY_BOT;
14436 		}
14437 		return (rval);
14438 	}
14439 
14440 	if (un->un_dp->options & ST_BSF) {
14441 		skip_cnt = 1 - infront;
14442 		/*
14443 		 * If we are going to end up at the beginning
14444 		 * of the file, we have to space one extra file
14445 		 * first, and then space forward later.
14446 		 */
14447 		end_fileno = -(count + skip_cnt);
14448 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
14449 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
14450 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
14451 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14452 			    "st_backward_space_files:EIO:back space fm failed");
14453 			rval = EIO;
14454 		}
14455 	} else {
14456 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
14457 			rval = EIO;
14458 		} else {
14459 			skip_cnt = end_fileno + infront;
14460 		}
14461 	}
14462 
14463 	/*
14464 	 * If we have to space forward, do so...
14465 	 */
14466 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
14467 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
14468 
14469 	if (rval == 0 && skip_cnt) {
14470 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
14471 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14472 			    "st_backward_space_files:EIO:space fm skip count");
14473 			rval = EIO;
14474 		} else if (infront) {
14475 			/*
14476 			 * If we had to space forward, and we're
14477 			 * not a tape that can backspace, mark state
14478 			 * as if we'd just seen a filemark during a
14479 			 * a read.
14480 			 */
14481 			if ((un->un_dp->options & ST_BSF) == 0) {
14482 				un->un_pos.eof = ST_EOF_PENDING;
14483 				un->un_pos.fileno -= 1;
14484 				un->un_pos.blkno = INF;
14485 			}
14486 		}
14487 	}
14488 
14489 	if (rval != 0) {
14490 		un->un_pos.pmode = invalid;
14491 	}
14492 
14493 	return (rval);
14494 }
14495 
14496 static int
14497 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
14498 {
14499 	int rval;
14500 
14501 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
14502 
14503 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14504 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
14505 
14506 	if (un->un_pos.pmode == legacy) {
14507 		/*
14508 		 * backward space file to beginning of file
14509 		 *
14510 		 * If a negative count (which implies a forward space op)
14511 		 * is specified, and we're at logical or physical eot,
14512 		 * bounce the request.
14513 		 */
14514 
14515 		if (un->un_pos.eof >= ST_EOT && count < 0) {
14516 			un->un_err_resid = count;
14517 			un->un_status = SUN_KEY_EOT;
14518 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14519 			    "st_ioctl : EIO : > EOT and count < 0");
14520 			return (EIO);
14521 		}
14522 		/*
14523 		 * physical tape position may not be what we've been
14524 		 * telling the user; adjust the request accordingly
14525 		 */
14526 		if (IN_EOF(un->un_pos)) {
14527 			un->un_pos.fileno++;
14528 			un->un_pos.blkno = 0;
14529 			count++;
14530 		}
14531 	}
14532 
14533 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14534 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14535 		    "st_ioctl : EIO : MTNBSF check den and wfm");
14536 		return (EIO);
14537 	}
14538 
14539 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14540 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
14541 
14542 	if (count <= 0) {
14543 		rval = st_forward_space_files(un, -count);
14544 	} else {
14545 		rval = st_backward_space_files(un, count, 0);
14546 	}
14547 	return (rval);
14548 }
14549 
14550 static int
14551 st_mtbsr_ioctl(struct scsi_tape *un, int num)
14552 {
14553 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
14554 
14555 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14556 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
14557 
14558 	if (un->un_pos.pmode == legacy) {
14559 		/*
14560 		 * backward space into inter-record gap
14561 		 *
14562 		 * If a negative count (which implies a forward space op)
14563 		 * is specified, and we're at logical or physical eot,
14564 		 * bounce the request.
14565 		 */
14566 		if (un->un_pos.eof >= ST_EOT && num < 0) {
14567 			un->un_err_resid = num;
14568 			un->un_status = SUN_KEY_EOT;
14569 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14570 			    "st_ioctl : EIO : MTBSR > EOT");
14571 			return (EIO);
14572 		}
14573 
14574 		if (num == 0) {
14575 			COPY_POS(&un->un_err_pos, &un->un_pos);
14576 			un->un_err_resid = 0;
14577 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14578 				un->un_status = SUN_KEY_EOF;
14579 			}
14580 			return (0);
14581 		}
14582 
14583 		/*
14584 		 * physical tape position may not be what we've been
14585 		 * telling the user; adjust the position accordingly.
14586 		 * bsr can not skip filemarks and continue to skip records
14587 		 * therefore if we are logically before the filemark but
14588 		 * physically at the EOT side of the filemark, we need to step
14589 		 * back; this allows fsr N where N > number of blocks in file
14590 		 * followed by bsr 1 to position at the beginning of last block
14591 		 */
14592 		if (IN_EOF(un->un_pos)) {
14593 			tapepos_t save;
14594 			optype lastop = un->un_lastop;
14595 
14596 			COPY_POS(&save, &un->un_pos);
14597 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
14598 			    == -1) {
14599 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14600 				    "st_write_fm : EIO : MTBSR can't space");
14601 				return (EIO);
14602 			}
14603 
14604 			COPY_POS(&un->un_pos, &save);
14605 			un->un_lastop = lastop;
14606 		}
14607 	}
14608 
14609 	un->un_pos.eof = ST_NO_EOF;
14610 
14611 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14612 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14613 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
14614 		return (EIO);
14615 	}
14616 
14617 	num = -num;
14618 	return (st_space_records(un, num));
14619 }
14620 
14621 static int
14622 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
14623 {
14624 	int rval;
14625 
14626 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
14627 
14628 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
14629 	if (rval == 0) {
14630 		un->un_pos.pmode = logical;
14631 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14632 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14633 		/*
14634 		 * Drive says invalid field in cdb.
14635 		 * Doesn't like space multiple. Position isn't lost.
14636 		 */
14637 		un->un_err_resid = cnt;
14638 		un->un_status = 0;
14639 		rval = ENOTTY;
14640 	} else {
14641 		un->un_err_resid = cnt;
14642 		un->un_pos.pmode = invalid;
14643 	}
14644 	return (rval);
14645 }
14646 
14647 static int
14648 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
14649 {
14650 	int rval;
14651 
14652 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
14653 
14654 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
14655 	if (rval == 0) {
14656 		un->un_pos.pmode = logical;
14657 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14658 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14659 		/*
14660 		 * Drive says invalid field in cdb.
14661 		 * Doesn't like space multiple. Position isn't lost.
14662 		 */
14663 		un->un_err_resid = cnt;
14664 		un->un_status = 0;
14665 		rval = ENOTTY;
14666 	} else {
14667 		un->un_err_resid = cnt;
14668 		un->un_pos.pmode = invalid;
14669 	}
14670 	return (rval);
14671 }
14672 
14673 #ifdef	__x86
14674 
14675 /*
14676  * release contig_mem and wake up waiting thread, if any
14677  */
14678 static void
14679 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
14680 {
14681 	mutex_enter(ST_MUTEX);
14682 
14683 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
14684 
14685 	cp->cm_next = un->un_contig_mem;
14686 	un->un_contig_mem = cp;
14687 	un->un_contig_mem_available_num++;
14688 	cv_broadcast(&un->un_contig_mem_cv);
14689 
14690 	mutex_exit(ST_MUTEX);
14691 }
14692 
14693 /*
14694  * St_get_contig_mem will return a contig_mem if there is one available
14695  * in current system. Otherwise, it will try to alloc one, if the total
14696  * number of contig_mem is within st_max_contig_mem_num.
14697  * It will sleep, if allowed by caller or return NULL, if no contig_mem
14698  * is available for now.
14699  */
14700 static struct contig_mem *
14701 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
14702 {
14703 	size_t rlen;
14704 	struct contig_mem *cp = NULL;
14705 	ddi_acc_handle_t acc_hdl;
14706 	caddr_t addr;
14707 	int big_enough = 0;
14708 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
14709 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
14710 
14711 	/* Try to get one available contig_mem */
14712 	mutex_enter(ST_MUTEX);
14713 
14714 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
14715 
14716 	if (un->un_contig_mem_available_num > 0) {
14717 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14718 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
14719 		/*
14720 		 * we failed to get one. we're going to
14721 		 * alloc one more contig_mem for this I/O
14722 		 */
14723 		mutex_exit(ST_MUTEX);
14724 		cp = (struct contig_mem *)kmem_zalloc(
14725 		    sizeof (struct contig_mem) + biosize(),
14726 		    alloc_flags);
14727 		if (cp == NULL) {
14728 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14729 			    "alloc contig_mem failure\n");
14730 			return (NULL); /* cannot get one */
14731 		}
14732 		cp->cm_bp = (struct buf *)
14733 		    (((caddr_t)cp) + sizeof (struct contig_mem));
14734 		bioinit(cp->cm_bp);
14735 		mutex_enter(ST_MUTEX);
14736 		un->un_contig_mem_total_num++; /* one more available */
14737 	} else {
14738 		/*
14739 		 * we failed to get one and we're NOT allowed to
14740 		 * alloc more contig_mem
14741 		 */
14742 		if (alloc_flags == KM_SLEEP) {
14743 			while (un->un_contig_mem_available_num <= 0) {
14744 				cv_wait(&un->un_contig_mem_cv,
14745 				    ST_MUTEX);
14746 			}
14747 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14748 		} else {
14749 			mutex_exit(ST_MUTEX);
14750 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14751 			    "alloc contig_mem failure\n");
14752 			return (NULL); /* cannot get one */
14753 		}
14754 	}
14755 	mutex_exit(ST_MUTEX);
14756 
14757 	/* We need to check if this block of mem is big enough for this I/O */
14758 	if (cp->cm_len < len) {
14759 		/* not big enough, need to alloc a new one */
14760 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
14761 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
14762 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
14763 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14764 			    "alloc contig_mem failure: not enough mem\n");
14765 			st_release_contig_mem(un, cp);
14766 			cp = NULL;
14767 		} else {
14768 			if (cp->cm_addr) {
14769 				/* release previous one before attach new one */
14770 				ddi_dma_mem_free(&cp->cm_acc_hdl);
14771 			}
14772 			mutex_enter(ST_MUTEX);
14773 			un->un_max_contig_mem_len =
14774 			    un->un_max_contig_mem_len >= len ?
14775 			    un->un_max_contig_mem_len : len;
14776 			mutex_exit(ST_MUTEX);
14777 
14778 			/* attach new mem to this cp */
14779 			cp->cm_addr = addr;
14780 			cp->cm_acc_hdl = acc_hdl;
14781 			cp->cm_len = len;
14782 
14783 			goto alloc_ok; /* get one usable cp */
14784 		}
14785 	} else {
14786 		goto alloc_ok; /* get one usable cp */
14787 	}
14788 
14789 	/* cannot find/alloc a usable cp, when we get here */
14790 
14791 	mutex_enter(ST_MUTEX);
14792 	if ((un->un_max_contig_mem_len < len) ||
14793 	    (alloc_flags != KM_SLEEP)) {
14794 		mutex_exit(ST_MUTEX);
14795 		return (NULL);
14796 	}
14797 
14798 	/*
14799 	 * we're allowed to sleep, and there is one big enough
14800 	 * contig mem in the system, which is currently in use,
14801 	 * wait for it...
14802 	 */
14803 	big_enough = 1;
14804 	do {
14805 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
14806 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14807 	} while (cp == NULL);
14808 	mutex_exit(ST_MUTEX);
14809 
14810 	/* we get the big enough contig mem, finally */
14811 
14812 alloc_ok:
14813 	/* init bp attached to this cp */
14814 	bioreset(cp->cm_bp);
14815 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
14816 	cp->cm_bp->b_private = (void *)cp;
14817 
14818 	return (cp);
14819 }
14820 
14821 /*
14822  * this is the biodone func for the bp used in big block I/O
14823  */
14824 static int
14825 st_bigblk_xfer_done(struct buf *bp)
14826 {
14827 	struct contig_mem *cp;
14828 	struct buf *orig_bp;
14829 	int ioerr;
14830 	struct scsi_tape *un;
14831 
14832 	/* sanity check */
14833 	if (bp == NULL) {
14834 		return (DDI_FAILURE);
14835 	}
14836 
14837 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14838 	if (un == NULL) {
14839 		return (DDI_FAILURE);
14840 	}
14841 
14842 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
14843 
14844 	cp = (struct contig_mem *)bp->b_private;
14845 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
14846 	cp->cm_bp = bp;
14847 
14848 	/* special handling for special I/O */
14849 	if (cp->cm_use_sbuf) {
14850 #ifndef __lock_lint
14851 		ASSERT(un->un_sbuf_busy);
14852 #endif
14853 		un->un_sbufp = orig_bp;
14854 		cp->cm_use_sbuf = 0;
14855 	}
14856 
14857 	orig_bp->b_resid = bp->b_resid;
14858 	ioerr = geterror(bp);
14859 	if (ioerr != 0) {
14860 		bioerror(orig_bp, ioerr);
14861 	} else if (orig_bp->b_flags & B_READ) {
14862 		/* copy data back to original bp */
14863 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
14864 		    bp->b_bcount - bp->b_resid);
14865 	}
14866 
14867 	st_release_contig_mem(un, cp);
14868 
14869 	biodone(orig_bp);
14870 
14871 	return (DDI_SUCCESS);
14872 }
14873 
14874 /*
14875  * We use this func to replace original bp that may not be able to do I/O
14876  * in big block size with one that can
14877  */
14878 static struct buf *
14879 st_get_bigblk_bp(struct buf *bp)
14880 {
14881 	struct contig_mem *cp;
14882 	struct scsi_tape *un;
14883 	struct buf *cont_bp;
14884 
14885 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14886 	if (un == NULL) {
14887 		return (bp);
14888 	}
14889 
14890 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
14891 
14892 	/* try to get one contig_mem */
14893 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
14894 	if (!cp) {
14895 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
14896 		    "Cannot alloc contig buf for I/O for %lu blk size",
14897 		    bp->b_bcount);
14898 		return (bp);
14899 	}
14900 	cont_bp = cp->cm_bp;
14901 	cp->cm_bp = bp;
14902 
14903 	/* make sure that we "are" using un_sbufp for special I/O */
14904 	if (bp == un->un_sbufp) {
14905 #ifndef __lock_lint
14906 		ASSERT(un->un_sbuf_busy);
14907 #endif
14908 		un->un_sbufp = cont_bp;
14909 		cp->cm_use_sbuf = 1;
14910 	}
14911 
14912 	/* clone bp */
14913 	cont_bp->b_bcount = bp->b_bcount;
14914 	cont_bp->b_resid = bp->b_resid;
14915 	cont_bp->b_iodone = st_bigblk_xfer_done;
14916 	cont_bp->b_file = bp->b_file;
14917 	cont_bp->b_offset = bp->b_offset;
14918 	cont_bp->b_dip = bp->b_dip;
14919 	cont_bp->b_error = 0;
14920 	cont_bp->b_proc = NULL;
14921 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
14922 	cont_bp->b_shadow = NULL;
14923 	cont_bp->b_pages = NULL;
14924 	cont_bp->b_edev = bp->b_edev;
14925 	cont_bp->b_dev = bp->b_dev;
14926 	cont_bp->b_lblkno = bp->b_lblkno;
14927 	cont_bp->b_forw = bp->b_forw;
14928 	cont_bp->b_back = bp->b_back;
14929 	cont_bp->av_forw = bp->av_forw;
14930 	cont_bp->av_back = bp->av_back;
14931 	cont_bp->b_bufsize = bp->b_bufsize;
14932 
14933 	/* get data in original bp */
14934 	if (bp->b_flags & B_WRITE) {
14935 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
14936 	}
14937 
14938 	return (cont_bp);
14939 }
14940 #else
14941 #ifdef __lock_lint
14942 static int
14943 st_bigblk_xfer_done(struct buf *bp)
14944 {
14945 	return (0);
14946 }
14947 #endif
14948 #endif
14949 
14950 static const char *eof_status[] =
14951 {
14952 	"NO_EOF",
14953 	"EOF_PENDING",
14954 	"EOF",
14955 	"EOT_PENDING",
14956 	"EOT",
14957 	"EOM",
14958 	"AFTER_EOM"
14959 };
14960 static const char *mode[] = {
14961 	"invalid",
14962 	"legacy",
14963 	"logical"
14964 };
14965 
14966 static void
14967 st_print_position(struct scsi_tape *un, const char *comment, tapepos_t *pos)
14968 {
14969 	ST_FUNC(ST_DEVINFO, st_print_position);
14970 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14971 	    "%s Position data:\n", comment);
14972 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14973 	    "Positioning mode = %s", mode[pos->pmode]);
14974 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14975 	    "End Of File/Tape = %s", eof_status[pos->eof]);
14976 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14977 	    "File Number      = 0x%x", pos->fileno);
14978 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14979 	    "Block Number     = 0x%x", pos->blkno);
14980 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14981 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
14982 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14983 	    "Partition Number = 0x%x", pos->partition);
14984 }
14985