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