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