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